I am having difficultly with syntax and structure of JSON objects/arrays.
{
"accounting" : [
{ "firstName" : "John",
"lastName" : "Doe",
"age" : 23 },
{ "firstName" : "Mary",
"lastName" : "Smith",
"age" : 32 }
],
"sales" : [
{ "firstName" : "Sally",
"lastName" : "Green",
"age" : 27 },
{ "firstName" : "Jim",
"lastName" : "Galley",
"age" : 41 }
]
}
I want to make a nested structure of objects and arrays that would house the following info:
{
"problems": [{
"Diabetes":[{
"medications":[{
"medicationsClasses":[{
"className":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}],
"className2":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}]
}]
}],
"labs":[{
"missing_field": "missing_value"
}]
}],
"Asthma":[{}]
}]}
But I have no idea what the right way to do this should be. Should I just be making JavaScript objects? Does JSON make sense for this project?
What is the correct syntax to set something like this up?
Here is my code so far:
$(document).ready(function() {
$.getJSON('js/orders.json', function(json) {
$.each(json.problems, function(index, order) {
$('.loadMeds').append('<p>' + order.name + '</p>')
});
});
});
-
I am just doing a local test by calling the JSON file with getJSON() in jQuery. This is just for testing in a production environment. Server is just Apache running PHP. (not terribly knowledgable with server stuff either...)Alex– Alex2012年05月10日 18:11:29 +00:00Commented May 10, 2012 at 18:11
-
1I'm not sure where you want to get with this question. You should structure the data in a way that you can process it easily and that depends on what you are doing with the data... do you have any particular technical question? Otherwise I don't see how this question is answerable.Felix Kling– Felix Kling2012年05月10日 18:28:49 +00:00Commented May 10, 2012 at 18:28
-
Basically I want an easy way to store strings of data for medications while keeping a strict and clean organizational strucure. I then want to pull this JSON file and output the values into a table.Alex– Alex2012年05月10日 18:30:26 +00:00Commented May 10, 2012 at 18:30
-
1then your problem is not with json, xml etc, they only meant to be used as temporary data structures, you should learn SQL and use postgeSQL :)gkaykck– gkaykck2012年05月10日 18:36:49 +00:00Commented May 10, 2012 at 18:36
-
@ Felix Kling Yes my TECHNICAL question was whether or not my syntax and structure was correct...Alex– Alex2012年05月10日 18:39:43 +00:00Commented May 10, 2012 at 18:39
5 Answers 5
The first code is an example of Javascript code, which is similar, however not JSON. JSON would not have 1) comments and 2) the var
keyword
You don't have any comments in your JSON, but you should remove the var
and start like this:
orders: {
The [{}]
notation means "object in an array" and is not what you need everywhere. It is not an error, but it's too complicated for some purposes. AssociatedDrug should work well as an object:
"associatedDrug": {
"name":"asprin",
"dose":"",
"strength":"500 mg"
}
Also, the empty object labs should be filled with something.
Other than that, your code is okay. You can either paste it into javascript, or use the JSON.parse()
method, or any other parsing method (please don't use eval)
Update 2 answered:
obj.problems[0].Diabetes[0].medications[0].medicationsClasses[0].className[0].associatedDrug[0].name
returns 'aspirin'. It is however better suited for foreaches everywhere
-
Thanks for the tip on eval()! I will make sure to avoid it :)Alex– Alex2012年05月10日 18:43:58 +00:00Commented May 10, 2012 at 18:43
-
4@Alex - Once you find out that
JSON.parse()
doesn't work in IE7, there's a method in jQuery to do it in all browsers.$.parseJSON()
Kevin B– Kevin B2012年05月10日 19:16:17 +00:00Commented May 10, 2012 at 19:16 -
that is what I ended up doing. Look at my solution I posted. I used nested $.each statements to grab the data I was looking for. Thanks for the help!Alex– Alex2012年05月11日 21:00:34 +00:00Commented May 11, 2012 at 21:00
I successfully solved my problem. Here is my code:
The complex JSON object:
{
"medications":[{
"aceInhibitors":[{
"name":"lisinopril",
"strength":"10 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"antianginal":[{
"name":"nitroglycerin",
"strength":"0.4 mg Sublingual Tab",
"dose":"1 tab",
"route":"SL",
"sig":"q15min PRN",
"pillCount":"#30",
"refills":"Refill 1"
}],
"anticoagulants":[{
"name":"warfarin sodium",
"strength":"3 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"betaBlocker":[{
"name":"metoprolol tartrate",
"strength":"25 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"diuretic":[{
"name":"furosemide",
"strength":"40 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"mineral":[{
"name":"potassium chloride ER",
"strength":"10 mEq Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}]
}
],
"labs":[{
"name":"Arterial Blood Gas",
"time":"Today",
"location":"Main Hospital Lab"
},
{
"name":"BMP",
"time":"Today",
"location":"Primary Care Clinic"
},
{
"name":"BNP",
"time":"3 Weeks",
"location":"Primary Care Clinic"
},
{
"name":"BUN",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Cardiac Enzymes",
"time":"Today",
"location":"Primary Care Clinic"
},
{
"name":"CBC",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Creatinine",
"time":"1 Year",
"location":"Main Hospital Lab"
},
{
"name":"Electrolyte Panel",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Glucose",
"time":"1 Year",
"location":"Main Hospital Lab"
},
{
"name":"PT/INR",
"time":"3 Weeks",
"location":"Primary Care Clinic"
},
{
"name":"PTT",
"time":"3 Weeks",
"location":"Coumadin Clinic"
},
{
"name":"TSH",
"time":"1 Year",
"location":"Primary Care Clinic"
}
],
"imaging":[{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
},
{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
},
{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
}
]
}
The jQuery code to grab the data and display it on my webpage:
$(document).ready(function() {
var items = [];
$.getJSON('labOrders.json', function(json) {
$.each(json.medications, function(index, orders) {
$.each(this, function() {
$.each(this, function() {
items.push('<div class="row">'+this.name+"\t"+this.strength+"\t"+this.dose+"\t"+this.route+"\t"+this.sig+"\t"+this.pillCount+"\t"+this.refills+'</div>'+"\n");
});
});
});
$('<div>', {
"class":'loaded',
html:items.join('')
}).appendTo("body");
});
});
-
13A little late for me to comment perhaps; but it strikes me that you're still using arrays a lot, even when it seems like there can only really be one object. For example, your top level
medications
property is an array of a single object. Unless you really need to account for multiple collections of medicine types here, I would drop the arrays altogether. Then you can just usevar x = medications.aceInhibitors
instead ofmedications[0].aceInhibitors
. (To me the second says "I'm taking the aceInhibitors property of the first medications object" - what does first mean here?)Andrzej Doyle– Andrzej Doyle2013年01月15日 12:23:15 +00:00Commented Jan 15, 2013 at 12:23 -
I don't think you need to put the properties of the med types in an array. Actually, there is a recommended way to build out JSON for performance. See property ordering google.github.io/styleguide/…Ronnie Smith– Ronnie Smith2017年02月06日 02:16:26 +00:00Commented Feb 6, 2017 at 2:16
Make sure you follow the language definition for JSON. In your second example, the section:
"labs":[{
""
}]
Is invalid since an object must be composed of zero or more key-value pairs "a" : "b"
, where "b"
may be any valid value. Some parsers may automatically interpret { "" }
to be { "" : null }
, but this is not a clearly defined case.
Also, you are using a nested array of objects [{}]
quite a bit. I would only do this if:
- There is no good "identifier" string for each object in the array.
- There is some clear reason for having an array over a key-value for that entry.
-
Labs is a just placeholder....This is just a rough concept. I know it needs a value.Alex– Alex2012年05月10日 18:20:50 +00:00Commented May 10, 2012 at 18:20
You can try use this function to find any object in nested nested array of arrays of kings.
Example
function findTByKeyValue (element, target){
var found = true;
for(var key in target) {
if (!element.hasOwnProperty(key) || element[key] !== target[key]) {
found = false;
break;
}
}
if(found) {
return element;
}
if(typeof(element) !== "object") {
return false;
}
for(var index in element) {
var result = findTByKeyValue(element[index],target);
if(result) {
return result;
}
}
};
findTByKeyValue(problems,{"name":"somethingElse","strength":"500 mg"}) =====> result equal to object associatedDrug#2
First, choosing a data structure(xml,json,yaml) usually includes only a readability/size problem. For example
Json is very compact, but no human being can read it easily, very hard do debug,
Xml is very large, but everyone can easily read/debug it,
Yaml is in between Xml and json.
But if you want to work with Javascript heavily and/or your software makes a lot of data transfer between browser-server, you should use Json, because it is pure javascript and very compact. But don't try to write it in a string, use libraries to generate the code you needed from an object.
Hope this helps.
-
I don't know what this means "use libraries to generate the code you needed from an object." Could you give an example?Alex– Alex2012年05月10日 18:19:09 +00:00Commented May 10, 2012 at 18:19
-
1@Alex For example, create the array/object in php, then use json_encode() to convert it to valid json.Kevin B– Kevin B2012年05月10日 18:24:04 +00:00Commented May 10, 2012 at 18:24
-
1create an object in php, then send it or embed it in your page with json_encode() method. The process is called serializing an object, sorry i forgot say it in question; itnewb.com/tutorial/Introduction-to-JSON-and-PHP/page3 here's an examplegkaykck– gkaykck2012年05月10日 18:24:06 +00:00Commented May 10, 2012 at 18:24
-
9I think that is highly subjective... I find JSON much easier to read than XML.Felix Kling– Felix Kling2012年05月10日 18:26:00 +00:00Commented May 10, 2012 at 18:26
-
@Felix Kling i found out it just now, because 2 people debugged Alex's code already :) I don't use xml anywhere but i still think it is easier to folow.gkaykck– gkaykck2012年05月10日 18:28:29 +00:00Commented May 10, 2012 at 18:28
Explore related questions
See similar questions with these tags.