Returning a specific JSON object using Express - json

So let's say I've got a massive JSON file, and the general structure is roughly like so:
{
"apples": { complex object },
"oranges": { complex object },
"grapes": { complex object }
}
Is there some way to specifically target an object to return while using express? As in, say, if someone made a simple get request to my server, it'd return specifically the given object(s). I know the syntax and concept is completely wrong in this instance but for lack of a better way to say it, something like...
let testData = 'testdata.json';
app.get('/thing', res => {
res.json(testData.oranges);
}
I know you can return the entire file, but that adds a good amount of loading time in this instance, and is impractical in this particular case.
Or, alternatively - would it be better to have node parse the JSON file and split it into an apples.json, oranges.json, etc files to use? Trying to understand A, the best practice for doing something like this, and B, the most effective way to translate this into a practical application for a medium sized project.
Any thoughts or advice along this line - even if it's a library recommendation - would be greatly appreciated.

It should work if you make a POST request caring the payload of the specific 'thing', and then returning an object based on that thing. Example:
let testData = {
"apples": { complex object },
"oranges": { complex object },
"grapes": { complex object }
};
app.post('/route', (req, res) => {
thing = req.body.thing;
res.json(testData[thing]);
}

This is a GET request for some data and essentially since the JSON file can be used as a key/value store to query for the desired response data.
Assuming the query parameter for specifying the desired key for the object to return is part then the following example would work:
const testData = require('./testdata.json');
app.get('/thing', (req, res) => res.json(testdata[req.query.part]);
Querying for /thing?part=apples would return testdata.apples in the response.

Related

How to save a JSON-object and use it in another request?

i'm currently trying to set up some JMeter testplans. I am pretty new to this (started a week ago) and don't have much programming experience either, so i hope you could help me in this case.
I already set up some http requests and have some simple JSON Extractor post processors to save some of the variables and use them with the "${variable}" notation.
But now i need to save and modify an object from a response to use that in the next http request.
My respose is a extremely big JSON object and the part im interested in looks something like this:
{
"payload": {
"workspace": {
"resultInstance": [
[{"part": "1"...}],
[{"part": "2"...}],
...
[{"part": "20"...}]
]
}
}
}
Note that for whatever reason these objects {"part":"1"...} are inside a nested array. And they are also pretty big.
I would like to safe those objects in a variable to use them in my next http request which should looks like this:
{
"instanceChange": {
"functionChecks": [
{"part": "1"...},
{"part": "2"...},
...
{"part": "20"...}
]
}
}
So what im really trying to find is a way to save all of the possible objects inside the nested array "resultInstance" and put them inside the non nested array "functionChecks".
I already looked inside the JMeter documentation but because of my poor programming background i cant find a way to realize this.
I think i need something like the JSR223 PostProcessor and "simply go through the resultInstance-array and use smth. like an getObject() on these", but i cant figure out the code i need and if its even possible to safe objects in variables in Jmeter.
Im pretty thankful for every bit of help or advice :).
Thanks in advance,
aiksn
Add JSR223 PostProcessor as a child of the request which returns the JSON response
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def request = ['instanceChange': ['functionChecks': response.payload.workspace.resultInstance]]
vars.put('request', new groovy.json.JsonBuilder(request).toPrettyString())
That's it, you should be able to refer the generated request body as ${request} where required
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
let response ={
"payload": {
"workspace": {
"resultInstance": [
[{"part": "1"...}],
[{"part": "2"...}],
...
[{"part": "20"...}]
]
}
}
};
let requestObj={
"instanceChange": {
"functionChecks": [
]
}
};
response.payload.workspace.resultInstance.forEach(myFunction);
myFunction(item, index) {
requestObj.instance.functionsCheck.push(item[0]);
}

How to efficiently separate a large dataset from an HTML page

I am attempting to implement a large searchable table of information on a static website- so using SQL or PHP is not possible. I am considering using Datatables, and converting the CSV into HTML. However I feel that having a nearly 3000 long HTML table isn't the most efficient way of doing this? What would be the best way of doing this? Thanks.
Have two files, an HTML page (i.e. the datatable your users will use) and a JSON file where you will store all your data.
Then, use fetch() to retrieve the data from the JSON file into the HTML page.
Say you wanted to display a datatable with two fields - names and DOBs - your JSON would look something like this:
{
[
["John Doe", "5.4.1996"],
["Jane Doe", "5.4.2006"]
]
}
On the HTML page:
let response = await fetch(url);
if (response.ok) { // if HTTP-status is 200-299
// get the response body (the method explained below)
let json = await response.json();
// TODO: put the retrieved json into the datable
} else {
alert("HTTP-Error: " + response.status);
}

How to send a list object from inside another list object in Node.js and Express

I am developing a REST API using node.js and express framework for the first time. I am struggling to fix a very small issue in Node.js and Express, but however, i am unable to do so. I have checked online for all the possible solutions and tried with what all options i know but i am unable to figure out the syntax for the same.
Background : I have one object named “Restaurant” and another object named “Menu” which has a foreign key reference to “Restaurant”.
Now, i have a requirement (common scenario), where i need to send a response to client in the below json format,
{
"Restaurants": [
{
"restaurantid":"5ad36b55c26b685030335e30",
"restaurantname": "ABC Restaurant",
"menus":[
{"menuname":"item1", "menucost":"10"},
{"menuname":"item2", "menucost":"20"}
},
{
"restaurantid":"9sd72b55c26b685030335e31",
"restaurantname": "XYZ Restaurant",
"menus":[
{"menuname":"item3", "menucost":"10"},
{"menuname":"item4", "menucost":"20"}
}
]
}
Problem - I am unable to figure out how to build the "menus" object in node.js and append it to my "menus" variable. I am able to send a response from a single table without any issues. Issue is only when i need to send the menu list based on restaurantid.
I need to get the menus based on the restaurantid.
Below is the code which i am using for returning data from mongodb.
router.get('/', checkAuth, (req, res, next) => {
Restaurant.find()
.exec()
.then(docs => {
res.status(200).json({
count: docs.length,
restaurants: docs.map(doc => {
return {
_id: doc._id,
restaurantname: doc.restaurantname,
menus: ????? <<**This is where i am stuck. Not able to figure out how to write the syntax**>>
}
})
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
});
Please help me with this problem.
Given that MongoDB is designed to store hierarchical documents with relational links between independent collections being something of an afterthought, this seems more like a schema design problem. A menu belongs to a single restaurant (since even individual franchises of a larger chain may have their own modifications or restrictions), so Menus could well work better as a property of Restaurants. It'd certainly be easier for your use case here since you wouldn't need to build anything. If you do need to look at menus alone you can always db.Restaurants.find({...}, {menus: true}); to project just that field.

TypeScript / Angular 2 creating a dynamic object deserializer

So I am coming from a background of C# where I can do things in a dynamic and reflective way and I am trying to apply that to a TypeScript class I am working on writing.
Some background, I am converting an application to a web app and the backend developer doesn't want to change the backend at all to accommodate Json very well. So he is going to be sending me back Json that looks like so:
{
Columns: [
{
"ColumnName": "ClientPK",
"Label": "Client",
"DataType": "int",
"Length": 0,
"AllowNull": true,
"Format": "",
"IsReadOnly": true,
"IsDateOnly": null
}
],
Rows:[
0
]
}
I am looking to write an Angular class that extends Response that will have a special method called JsonMinimal which will understand this data and return an object for me.
import { Response } from "#angular/http";
export class ServerSource
{
SourceName: string;
MoreItems: boolean;
Error: string;
ExtendedProperties: ExtendedProperty[];
Columns: Column[];
}
export class ServerSourceResponse extends Response
{
JsonMinimal() : any
{
return null; //Something that will be a blank any type that when returned I can perform `object as FinalObject` syntax
}
}
I know StackOverflow isn't for asking for complete solutions to problems so I am only asking what is one example taking this example data and creating a dynamic response that TypeScript isn't going to yell at me for. I don't know what to do here, this developer has thousands of server-side methods and all of them return strings, in the form of a JSON or XML output. I am basically looking for a way to take his column data and combine it with the proper row data and then have a bigger object that holds a bunch of these combined object.
A usage case here after that data has been mapped to a basic object would be something like this.
Example:
var data = result.JsonMinimal() as LoginResponse; <-- Which will map to this object correctly if all the data is there in a base object.
var pk = data.ClientPK.Value;
I'm not exactly sure I understand, but you may want to try a simple approach first. Angular's http get method returns an observable that can automatically map the response to an object or an array of objects. It is also powerful enough to perform some custom mapping/transformation. You may want to look at that first.
Here is an example:
getProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
Here I'm mapping a json response to an array of Product objects I've defined with an IProduct interface. Since this is just a "lambda" type function, I could add any amount of code here to transform data.

Angular2 HTTP Providers, get a string from JSON for Amcharts

This is a slightly messy questions. Although it appears I'm asking question about amCharts, I really just trying to figure how to extract an array from HTTP request and then turn it into a variable and place it in to 3-party javacript.
It all starts here, with this question, which was kindly answered by AmCharts support.
As one can see from the plnker. The chart is working. Data for the chart is hard coded:
`var chartData = [{date: new Date(2015,2,31,0,0,0, 0),value:372.10,volume:2506100},{date: new Date(2015,3,1,0, 0, 0, 0),value:370.26,volume:2458100},{date: new Date(2015,3,2,0, 0, 0, 0),value:372.25,volume:1875300},{date: new Date(2015,3,6,0, 0, 0, 0),value:377.04,volume:3050700}];`
So we know the amCharts part works. Know where the problem is changing hard coded data to a json request so it can be dynamic. I don't think this should be tremendously difficult, but for the life of me I can't seem figure it out.
The first issue is I can't find any documentation on .map, .subscribe, or .observable.
So here is a plunker that looks very similar to the first one, however it has an http providers and injectable. It's broken, because I can't figure out how to pull the data from the service an place it into the AmCharts function. I know how pull data from a http provider and display it in template using NgFor, but I don't need it in the template (view). As you can see, I'm successful in transferring the data from the service, with the getTitle() function.
this.chart_data =_dataService.getEntries();
console.log('Does this work? '+this.chart_data);
this.title = _dataService.getTitle();
console.log('This works '+this.title);
// Transfer the http request to chartData to it can go into Amcharts
// I think this should be string?
var chartData = this.chart_data;
So the ultimate question is why can't I use a service to get data, turn that data into a variable and place it into a chart. I suspect a few clues might be in options.json as the json might not be formatted correctly? Am I declaring the correct variables? Finally, it might have something to do with observable / map?
You have a few things here. First this is a class, keep it that way. By that I mean to move the functions you have inside your constructor out of it and make them methods of your class.
Second, you have this piece of code
this.chart_data =_dataService.getEntries().subscribe((data) => {
this.chart_data = data;
});
What happens inside subscribe runs asynchronously therefore this.chart_data won't exist out of it. What you're doing here is assigning the object itself, in this case what subscribe returns, not the http response. So you can simply put your library initialization inside of the subscribe and that'll work.
_dataService.getEntries().subscribe((data) => {
if (AmCharts.isReady) {
this.createStockChart(data);
} else {
AmCharts.ready(() => this.createStockChart(data));
}
});
Now, finally you have an interesting thing. In your JSON you have your date properties contain a string with new Date inside, that's nothing but a string and your library requires (for what I tested) a Date object, so you need to parse it. The problem here is that you can't parse nor stringify by default a Date object. We need to convert that string to a Date object.
Look at this snippet code, I used eval (PLEASE DON'T DO IT YOURSELF, IS JUST FOR SHOWING PURPOSES!)
let chartData = [];
for(let i = 0; i < data[0].chart_data.length; i++) {
chartData.push({
// FOR SHOWING PURPOSES ONLY, DON'T TRY IT AT HOME
// This will parse the string to an actual Date object
date : eval(data[0].chart_data[i].date);
value : data[0].chart_data[i].value;
volume : data[0].chart_data[i].volume;
});
}
Here what I'm doing is reconstructing the array so the values are as required.
For the latter case you'll have to construct your json using (new Date('YOUR DATE')).toJSON() and you can parse it to a Date object using new Date(yourJSON) (referece Date.prototype.toJSON() - MDN). This is something you should resolve in your server side. Assuming you already solved that, your code should look as follows
// The date property in your json file should be stringified using new Date(...).toJSON()
date : new Date(data[0].chart_data[i].date);
Here's a plnkr with the evil eval. Remember, you have to send the date as a JSON from the server to your client and in your client you have to parse it to a Date.
I hope this helps you a little bit.
If the getEntries method of DataService returns an observable, you need to subscribe on it to get data:
_dataService.getEntries().subscribe(
(data) => {
this.chart_data = data;
});
Don't forget that data are received asynchronously from an HTTP call. The http.get method returns an observable (something "similar" to promise) will receive the data in the future. But when the getEntries method returns the data aren't there yet...
The getTitle is a synchronous method so you can call it the way you did.