How to choose a json structure for data? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In this case the first variable is always the ID, the second variable is always the OCR number and the third number is always the amount. Then would it make any difference to do either in this way:
{
"Transactions": [
"23/2/2014 # 16:48:8",
[
[
"ID",
"1"
],
[
"OCR",
"123456789"
],
[
"Amount",
"100"
]
],
[
[
"ID",
"2"
],
[
"OCR",
"987654321"
],
[
"Amount",
"20"
]
]
]
}
Or the equivalent input with just the input data since we know that the index will be the same for the different values:
{
"Transactions": [
"23/2/2014 # 16:48:8",
[
[
"1"
],
[
"123456789"
],
[
"100"
]
],
[
[
"2"
],
[
"987654321"
],
[
"20"
]
]
]
}
Or even simpler:
{
"Transactions": [
"23/2/2014 # 16:48:8",
[
"1",
"123456789",
"100"
],
[
"2",
"987654321",
"20"
]
]
}
Or minimally:
{
"23/2/2014 # 16:48:8": [
[
"1",
"123456789",
"100"
],
[
"2",
"987654321",
"20"
]
]
}
But I don't thnk that the following is good style even though it would work if you know which element is which and just post an array:
{
"23/2/2014 # 16:48:8": [
123456789,
100,
987654321,
20
]
}
Or just an array (that is also valid json and contains all we need to know):
[
123456789,
100,
987654321,
20
]
Even though all the exampled appear to be valid json, it might be preferred to go in either direction, either a structure which is less readable and monimally just an array, or a structure that is named and more complex but also more readable even though a number can represent what time it is, it might be preferable to store it as a string and similar to have a label what some data is.
In my last example you must know that every second element is an amount and every other element is an OCR reference.
There is also an alternative that is valid json like this:
{
"23/2/2014 # 16:48:8": [
[
{
"OCR": 123456789
},
{
"Amount": 100
}
],
[
{
"OCR": 987654321
},
{
"Amount": 200
}
]
]
}
So I'm not sure how to represent the elements and lists.

Only you can decide what it should look like in the end, but here are a couple of suggestions...
Stay away from using data as keys...
{
"23/2/2014 # 16:48:8": []
}
Instead do something like this...
{
"timestamp": "23/2/2014 # 16:48:8",
"data": []
}
And your use of arrays seem better suited as objects. Here's an example of what I think is an acceptable representation...
{
"transactions": [
{ "id": 1, "timestamp": "23/2/2014 # 16:48:8", "ocr": 12345678, "amount": 500 },
{ "id": 2, "timestamp": "23/2/2014 # 16:48:9", "ocr": 345435, "amount": 200}
]
}

The best format really depends upon how you want to consume the data. But, generally I think of data like this as a collection of objects where each transaction is an object that has properties. In that vein, something like an array of transactions would make sense:
{
"Transactions": [
{
"time": "23/2/2014 # 16:48:8",
"id": "1",
"ocr": "123456789",
"amount": "100"
},
{
"time": "23/2/2014 # 16:48:8",
"id": "2",
"ocr": "987654321",
"amount": "200"
}
]
}
This lets you loop through the transactions and then access each of the properties of each transaction.

Related

How can I store mapping orders in BBDD and then eval them

I'm trying to store in MongoDB one document with an object with the properties I want to map latter. My idea it's to create a function that will receive 2 params. First the object where I got to find the mapping, and second the object where I have to take the info from.
For example I want to store this JSON (that would be the first parameter in the function):
{
"name": "client.firstName",
"surname": "client.surname",
"age": "client.age",
"skills": [
{
"skillName": "client.skills[index].name",
"level": "client.skills[index].levelNumber",
"categories": [
{
"categoryName": "client.skills[index].categories[index].name",
"isImportant": "client.skills[index].categories[index].important"
}
]
}
]
}
And the second paramenter would be something like this (it's the object where you find the information.
{
"client": {
"firstName": "Jake",
"surname": "Long",
"age": 20,
"skills": [
{
"name": "Fly",
"level": 102,
"categories": [
{
"name": "air",
"important": true
},
{
"name": "superpower",
"important": false
}
]
},
{
"name": "FastSpeed",
"level": 163,
"categories": [
{
"name": "superpower",
"important": false
}
]
}
]
}
}
The idea it's: with de paths that I have in the first object, find it in the second one.. The problem I found it's when I have arrays, because when I defined the mapping rules I don't know how many positions will have the array I want to map. So in the mapping object (first) I'll only define the path but I'll not put it with the same lenght of the secondone because I don't know how much it will have.

how can i extract axios data from string?

This is response data from server
[{"username": "harry"}][{"id": 1, "name": "playlist1", "tag": "genre"}, {"id": 2, "name": "playlist1", "tag": "genre"}, {"id": 3, "name": "playlist3", "tag": "genre"}][{"1": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}, {"2": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af", "https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}, {"3": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af", "https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}]
With axios, data comes as a string in the format as above.
There are three arrays in the above string, and I want to extract each one separately and store it in a variable.
It doesn't converted to JSON. How can I get the data of username and the data of the second array? I tried to access it by index, but since it is a string format, it is accessed one by one letter
You should get response fixed as sugguested by #certainperformance and #ambianbeing, but if you can't and still want to extract data from this string response you can do it by doing something like this
const axiosResponse = `[{"username": "harry"}][{"id": 1, "name": "playlist1", "tag": "genre"}, {"id": 2, "name": "playlist1", "tag": "genre"}, {"id": 3, "name": "playlist3", "tag": "genre"}][{"1": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}, {"2": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af", "https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}, {"3": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af", "https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}]`;
const result = JSON.stringify(
JSON.parse('{ "data": [' + axiosResponse.split('][').join('],[') + ']}').data[1]
);
console.log(result);
The response you have posted, is not a string. It appears to be three arrays, each containing x amount of objects.
A string can be identified, by being enclosed in either double: " " or single qoutes: ' '.
You can identify the arrays by the opening and closing square brackets: [ ].
The objects can be identified by the opening and closing curly brackets: { }.
Here is a bit more readable version of your response. I have annotated each top level array, with a comment, for easier identification.
// array 1
[
{"username": "harry"}
]
// array 2
[
{ "id": 1, "name": "playlist1", "tag": "genre" },
{ "id": 2, "name": "playlist1", "tag": "genre" },
{ "id": 3, "name": "playlist3", "tag": "genre" }
]
// array 3
[
{
"1": [
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"
]
},
{
"2": [
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af",
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"
]
},
{
"3": [
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af",
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"
]
}
]
The third array appears to contain an object, with a list within it. Like somebody else mentioned earlier, this seems like faulty data, and I would have a look at the source, instead of trying to parse it. That being said, it isn't impossible to loop through each list, and extract the data, but it wouldn't be the correct way of doing it.

How can I extract nested value in JSON and initialize to a JS variable

my question is above and I am trying like for 45mins to extract the value under "distance" below, but I fail at every try. I hope you guys can help me.
{
"destination_addresses": [
"XXXXXXXX 60, 13XXX Berlin, Germany"
],
"origin_addresses": [
"XXXXXXX Str. 67, 10XXX Berlin, Germany"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}
]
}
],
"status": "OK"
}
So I need the value under rows --> elements --> distance then value. I tried something like this in JavaScript:
var payload = JSON.parse(body)
console.log(payload.rows["elements"].distance.value)
Thanks! :)
Süleyman Demir
let distance = payload.rows[0].elements[0].distance.value
console.log(payload)
console.log(distance)
Please note that the data is a mix of nested arrays and objects, which are different data structures in javascript. You can access an object's property by typing its name followed by a dot and the name of the property (object_name.property_name). You can access an array's element by typing the element index in square brackets next to the array's name (array_name[element_number]).
In our case we access the property "rows" which is an array of the object "payload" - payload.rows. Then we access the element number [0] of this array by typing [0] next to the property's name - payload.rows[0]. We get another object which has the property "elements" in it - payload.rows[0].elements . This property stores another array and we access its first element again -
payload.rows[0].elements[0]. We get another object and access the property "distance" which returns finally return another object that holds the property "value" we are looking for - payload.rows[0].elements[0].distance.value
Source https://eloquentjavascript.net/04_data.html
Your question was not clear, I assume that you will have multiple rows and multiple elements. There is my solution according to what I understand.
payload.rows.forEach(x=> x.elements.forEach(y => console.log(y.distance.value)))
Try like below
var body = {
"destination_addresses": ["XXXXXXXX 60, 13XXX Berlin, Germany"],
"origin_addresses": ["XXXXXXX Str. 67, 10XXX Berlin, Germany"],
"rows": [{
"elements": [{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}]
}],
"status": "OK"
};
var payload = JSON.parse(JSON.stringify(body));
payload.rows.forEach(row => row.elements.forEach(elem => console.log("Distance : ", elem.distance.value)))
I don't know exactly what you want, but you can get the distance object with something like that:
const payload = {
"destination_addresses": [
"XXXXXXXX 60, 13XXX Berlin, Germany"
],
"origin_addresses": [
"XXXXXXX Str. 67, 10XXX Berlin, Germany"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}
]
}
],
"status": "OK"
}
let distance = payload.rows[0].elements.map(element => {
return {
distance: element.distance
}
});
// Map returns an array, so you can get the object using the index:
console.log(distance[0]);
// If you want only the value:
console.log(distance[0].distance.value);
If you want, you can also use Object.assign or something like that to avoid getting the value by the index.
Hope it helped!
var payload = JSON.parse(body);
console.log(payload.rows[0]["elements"][0].distance.value);

Push complex json record into a json variable using javascript

I've been trying to push a complex json data record into a json variable. This is the code I tried to do so.
var marks=[];
var studentData="student1":[{
"term1":[
{"LifeSkills":[{"obtained":"17","grade":"A","gp":"5"}]},
{"Work":[{"obtained":"13","grade":"A","gp":"5"}]}
]
"term2":[
{"LifeSkills":[{"obtained":"17","grade":"A","gp":"5"}]},
{"Work":[{"obtained":"13","grade":"A","gp":"5"}]}
]
}];
marks.push(studentData);
But it doesn't push anything to the json array.Can anyone please help me to get rid of this.
DEMO
here i corrected your json and checkout the demo
var studentData={
"student1": [
{
"term1": [
{
"LifeSkills": [
{
"obtained": "17",
"grade": "A",
"gp": "5"
}
]
},
{
"Work": [
{
"obtained": "13",
"grade": "A",
"gp": "5"
}
]
}
],
"term2": [
{
"LifeSkills": [
{
"obtained": "17",
"grade": "A",
"gp": "5"
}
]
},
{
"Work": [
{
"obtained": "13",
"grade": "A",
"gp": "5"
}
]
}
]
}
]
}
var marks=[];
marks.push(studentData);
console.log(marks);
it successfully pushed into marks array
var marks=[];
var studentData={"student1":[{
"term1":[
{"LifeSkills":[{"obtained":"17","grade":"A","gp":"5"}]},
{"Work":[{"obtained":"13","grade":"A","gp":"5"}]}
],
"term2":[
{"LifeSkills":[{"obtained":"17","grade":"A","gp":"5"}]},
{"Work":[{"obtained":"13","grade":"A","gp":"5"}]}
]
}]};
marks.push(studentData);
console.log(marks);
Here you go.
You have make syntax error in the JSON object definition. Generally JSON object to be placed inside curly braces. And also comma is required between items. I have posted correct JSON definition of your studentData. Then you are able to push the JSON object to other array.
var studentdata={"student1":[{"term1":[
{"LifeSkills":[{"obtained":"17","grade":"A","gp":"5"}]},
{"Work":[{"obtained":"13","grade":"A","gp":"5"}]}
]}],"term2":[
{"LifeSkills":[{"obtained":"17","grade":"A","gp":"5"}]},
{"Work":[{"obtained":"13","grade":"A","gp":"5"}]}
]}
Regards,
Sunil Prabakar C

basic java script json child array decoding

I have been teaching myself some basic javascript the last couple of days and playing with google scripting as well as the twitter api and have come a bit unstuck on something that should probably be quite easy!
For sake of easierness of typing so my return from twitter api looks like this
[id:1
connections: "NONE"
],
[id:2
connections: ["following", "followed_by"]
]
What I am trying to do is find out out if the key 'following' exists for user 2, but I am really struggling!
The twitter api docs show an examples json as
[
{
"name": "Taylor Singletary",
"id_str": "819797",
"id": 819797,
"connections": [
"none"
],
"screen_name": "episod"
},
{
"name": "Twitter API",
"id_str": "6253282",
"id": 6253282,
"connections": [
"following",
"followed_by"
],
"screen_name": "twitterapi"
}
]
Can any point me in the correct direction?, how do I find out if following exists?
Thanks
connections: ["following", "followed_by"] is an array. To check if an array contains a special value you can use indexOf():
var a = [1, 2, "three", 44];
a.indexOf(1); // 0
a.indexOf(2); // 1
a.indexOf("three"); // 2
a.indexOf(22); // -1
So to check if "following" is in the array:
if (connections.indexOf("following") !== -1) {
// yeah!
} else {
// doh!
}
To count the objects in your example which have "following":
var o = [
{
"name": "Taylor Singletary",
"id_str": "819797",
"id": 819797,
"connections": [
"none"
],
"screen_name": "episod"
},
{
"name": "Twitter API",
"id_str": "6253282",
"id": 6253282,
"connections": [
"following",
"followed_by"
],
"screen_name": "twitterapi"
}
];
var withFollowing = o.filter(
function (i) {
return i.connections.indexOf("following") !== -1;
}
);
// filter() returns a new array
// this new array has only the elements for which the function returns true
console.log(withFollowing.lenght);

Categories