I'm new to nodejs and am trying to write a Json parser that will take data from a Json API, allow me to grab the data I want (some of this data I will transform) and then write to a Json file.
I have discovered the map command which is extracting the raw data and this is giving me an array for example
data['home_team'] = json['data'].map(smdata => smdata.localTeam.data.name);
data['awayid'] = json['data'].map(smdata => smdata.visitorTeam.data.id);
data['away_team'] = json['data'].map(smdata => smdata.visitorTeam.data.name);
And this works perfectly, now I'm left with an array which I want to turn into a Json file, I can of course just run a FOR loop and iterate through each of the entries and write to a file but I wondered if there was a more efficent way to do this
Thanks
Take a look at JSON.stringify to turn your data into a string you can write to a file.
In your comments below, you provide an invalid JS structure, an array with keys - maybe a typo with square braces (array) rather than curly braces (object). Or maybe note that Array map returns an array, so you may wish to look at Array.reduce, depending on your data.
let data = {
islive: [90, 90, null, null],
ls: [1, 1, 1, 1],
time: [90, 90, null, null],
status: ['FT', 'FT', 'NS', 'NS'],
starttime: [1616036700, 1616050800, 1616058000, 1616058900],
matchid: [17706353, 17926675, 17869155, 17926676]
};
// Dump it as JSON:
console.log(JSON.stringify(data));
// Pretty print with 2 space indent:
console.log(JSON.stringify(data, {}, 2));
// Write it to file 'my.json':
const fs = require('fs');
fs.writeFileSync(
'my.json',
JSON.stringify(data)
);
Outputs:
{"islive":[90,90,null,null],"ls":[1,1,1,1],"time":[90,90,null,null],"status":["FT","FT","NS","NS"],"starttime":[1616036700,1616050800,1616058000,1616058900],"matchid":[17706353,17926675,17869155,17926676]}
{
"islive": [
90,
90,
null,
null
],
"ls": [
1,
1,
1,
1
],
"time": [
90,
90,
null,
null
],
"status": [
"FT",
"FT",
"NS",
"NS"
],
"starttime": [
1616036700,
1616050800,
1616058000,
1616058900
],
"matchid": [
17706353,
17926675,
17869155,
17926676
]
}
Related
I have this simple variable which I am trying to extract data from. I've parsed it successfully to a json object and tried to print a value based on it a key. But all it says is "undefined". This example I provided is actually a snippet of the json I am trying to manipulate. The full file is actually a json object where one of the elements contains an array of many json objects (these are the ones I ultimately have to access). I have watched countless tutorials and have followed them exactly, but none seem to have this issue.
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
JSON.parse(x);
console.log(x.status);
Can anybody suggest something I may be doing wrong? Thank you!
JSON.parse Return value
The Object, Array, string, number, boolean, or null value
corresponding to the given JSON text. - MDN
You have to assign the parsed result to some variable/constant from where you can use later that parsed value and then use that variable to extract data as:
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
const parsedData = JSON.parse(x);
console.log(parsedData.status);
or you can directly get value one time after parsed as:
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
console.log(JSON.parse(x).status);
I want to convert this:
[null, 1890, null, NGU]
...into this:
[[], [1890], [], [NGU]]
I've tried creating a new array and pushing values to it, but that just ends up looking the same. Honestly, I'm unsure of what to even call what I'm trying to create. Is it a two-dimensional array or an array of objects?
This is for a google app script and the documentation calls it a two-dimensional array of values.
var arr = [null, 1890, null, 'NGU']
var arr2d = arr.map(x => [x])
console.log(arr2d) // output --> [ [ null ], [ 1890 ], [ null ], [ 'NGU' ] ]
I need to build diagram,
There is an array with objects for chart data
"graphicDetails": [
{
"hour": 0,
"businessOperationPlansTotalDemand": 8.201753196882908,
"employeesCount": 0,
"businessOperationPlans": [
{
"name": "operation0",
"value": 5.999355066255491
},
]
},
{
"hour": 1,
"businessOperationPlansTotalDemand": 7.450044665662842,
"employeesCount": 3,
"businessOperationPlans": []
},
{
"hour": 2,
"businessOperationPlansTotalDemand": 5.814536267254451,
"employeesCount": 5,
....
To draw it in the chart library (chartjs) I need the object to be with the fields {x: hour, y: businessOperationPlansTotalDemand, etc.}. Example:
data: [
{ x: 0, y: 5.815634, businessOperationPlans: [{operation: ...}] ,
{ x: 1, y: 2.23232, businessOperationPlans: [{operation2: ...}] ,
...
]
I know i can use forEach or something like this to rename properties, but what is the right way to resolve this task? maybe i should ask backend to make data in other format?
Maybe I need to create a new array based on this with other properties and put it in the computed field in Vue? How can i do this?
You can use map
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
const graphicDetails = [{
"hour": 0,
"businessOperationPlansTotalDemand": 8.201753196882908,
"employeesCount": 0,
"businessOperationPlans": [{
"name": "operation0",
"value": 5.999355066255491
}, ]
},
{
"hour": 1,
"businessOperationPlansTotalDemand": 7.450044665662842,
"employeesCount": 3,
"businessOperationPlans": []
}
];
const newData = graphicDetails.map(a=>{
return {x:a.hour,y:a.businessOperationPlansTotalDemand,businessOperationPlans:a.businessOperationPlans };
})
console.log(newData);
You can create a new array and design as per your new array structure . If you are using any backend , create the structure from there and process the same in computed , rather put it in mounted so it will load the same in the component gets mounted . Best way will be to process the data-set from backend .
I want to display like convert JSON data to array objects how can solve this problem using jquery or js?
JSON data :
[{
"new": 122,
"old": 3389,
"boarding": 1,
"aws": 10,
"azure": 12,
"cli": 41
}];
To array object:
[
["new", 122],
["old", 3389],
["boarding", 1]
]
one more pattern I need it I have an array like this in Ruby
[37,
3,
261,
1,
0,
1457]
to convert into add as key entry static
[
["new",37],
["old",3],
["boarding",1]
["aws",0]
["azure",1457]
]
Firstly note that you do not need jQuery at all for this. jQuery is primarily a tool for amending the DOM. To work with data structures like this native JS is all you need.
To achieve what you require, you can use Object.keys() to get the keys of the 0th object in your original array, then you can loop over them using map() to build a new 2 dimensional array from that data:
var originalArr = [{
"new": 122,
"old": 3389,
"boarding": 1,
"aws": 10,
"azure": 12,
"cli": 41
}];
var newArr = Object.keys(originalArr[0]).map(function(key) {
return [key, originalArr[0][key]];
});
console.log(newArr);
Its simple enough. Just enter the array into Object.entries(). like this Object.entries(originalArr[0])
A simple one-line alternative:
const data = [{
"new": 122,
"old": 3389,
"boarding": 1,
"aws": 10,
"azure": 12,
"cli": 41
}];
const result = Object.keys(data[0]).map(k => ([k, data[0][k]]));
console.log(result);
I have an array of JSON objects received from an API call.
data = [{
"notificationId": null,
"notificationText": "xXXX YYY",
"notificationType": "typeA",
"fromId": 2,
"toId": 9,
"timestampCreated": {
"epochSecond": 1493898875,
"nano": 0
}},
{
"notificationId": null,
"notificationText": "YYYYYYY,
"notificationType": "typeB",
"fromId": 3,
"toId": 9,
"timestampCreated": {
"epochSecond": 1493898903,
"nano": 0
}}
]
I want the individual Notification objects, by iterating over this array
My Notification interface looks like below
interface Notification {
notificationId: number;
notificationText : string;
notificationType : string;
fromId:number;
toId:number;
timestampCreated: Date ;
}
notif: Notification[] = [];
.
.
this.notif =data;
for(var i=0;i<this.notif.length ;i++){
console.log("notification text at "+this.notif[i].notificationText);
//this gives undefined
//and it loops through all the characters of the data
// not just twice
}
Can some one help, I am very new to angular2/ typescript world.
I am answering this as I figured out what was the problem. In the above snippet, the array of objects is actually array of JS objects not JSON objects. So I needed to parse the objects before I could use them as JSON. A simple JSON.parse(data) fixed the issue.