You don't need to use arrays.
JSON values can be arrays, objects, or primitives (numbers or strings).
You can write JSON like this:
{
"stuff": {
"onetype": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"othertype": {"id":2,"company":"ACME"}
},
"otherstuff": {
"thing": [[1,42],[2,2]]
}
}
You can use it like this:
obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1] //thing is a nested array or a 2-by-2 matrix.
//I'm not sure whether you intended to do that.
Answer from SLaks on Stack OverflowYou don't need to use arrays.
JSON values can be arrays, objects, or primitives (numbers or strings).
You can write JSON like this:
{
"stuff": {
"onetype": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"othertype": {"id":2,"company":"ACME"}
},
"otherstuff": {
"thing": [[1,42],[2,2]]
}
}
You can use it like this:
obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1] //thing is a nested array or a 2-by-2 matrix.
//I'm not sure whether you intended to do that.
Every object has to be named inside the parent object:
{ "data": {
"stuff": {
"onetype": [
{ "id": 1, "name": "" },
{ "id": 2, "name": "" }
],
"othertype": [
{ "id": 2, "xyz": [-2, 0, 2], "n": "Crab Nebula", "t": 0, "c": 0, "d": 5 }
]
},
"otherstuff": {
"thing":
[[1, 42], [2, 2]]
}
}
}
So you cant declare an object like this:
var obj = {property1, property2};
It has to be
var obj = {property1: 'value', property2: 'value'};
How can I access a nested array within a JSON file?
Nested JSON Array of Arrays
JSON object to array of nested JSON
create nested json from array of objects dynamically
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
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");
});
});
The solution below uses the following approach:
- Index each item into an object by their respective
titlevalue from theallCardscollection by using Array.prototype.reduce(). - Use Array.prototype.filter() to retain the
rootitems in the collection, while at the same time assign each item as a child to their respective parents if they do exist in theindexedvariable.
var allCards = [
{ title: "A", parent_id: "root", has_children: true},
{ title: "A1", parent_id: "A", has_children: true},
{ title: "A11", parent_id: "A1", has_children: false},
{ title: "A12", parent_id: "A1", has_children: false},
{ title: "A13", parent_id: "A1", has_children: false},
{ title: "B", parent_id: "root", has_children: true},
{ title: "B1", parent_id: "A", has_children: true},
{ title: "B11", parent_id: "B1", has_children: false},
{ title: "B12", parent_id: "B1", has_children: false},
{ title: "B13", parent_id: "B1", has_children: false}
];
// index each item by title
var indexed = allCards.reduce(function(result, item) {
result[item.title] = item;
return result;
}, {});
// retain the root items only
var result = allCards.filter(function(item) {
// get parent
var parent = indexed[item.parent_id];
// make sure to remove unnecessary keys
delete item.parent_id;
delete item.has_children;
// has parent?
if(parent) {
// add item as a child
parent.children = (parent.children || []).concat(item);
}
// This part determines if the item is a root item or not
return !parent;
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Here is one way of doing it. Iterate the array of objects, building a new object for each one and store it in a cache so you can directly modify that object when its children are processed. Parents must appear before children for this to work, otherwise you'd have to build in multiple passes.
// define data array
var data = [
{ title: "A", parent_id: "root",has_children: true},
{ title: "A1", parent_id: "A",has_children: true},
{ title: "A11", parent_id: "A1",has_children: false},
{ title: "A12", parent_id: "A1",has_children: false},
{ title: "A13", parent_id: "A1",has_children: false},
{ title: "B", parent_id: "root",has_children: true},
{ title: "B1", parent_id: "A",has_children: true},
{ title: "B11", parent_id: "B1",has_children: false},
{ title: "B12", parent_id: "B1",has_children: false},
{ title: "B13", parent_id: "B1",has_children: false}
];
var root = {};
var parentCache = {};
// for each element definition in the data array
for (var i = 0; i < data.length; i++) {
var element = data[i];
var title = element.title;
// XXX - check for duplicate title here.
// create a new object and initialize
var newObj = {"title" : title};
if (element.has_children) {
newObj["children"] = [];
}
// put this object into its parent
if (element.parent_id === "root") {
root[title] = newObj;
} else {
// XXX - if the parent isn't defined first this will fail
var parent = parentCache[element.parent_id];
parent.children.push(newObj);
}
// store this object in case it is a parent
parentCache[title] = newObj;
}
console.log(JSON.stringify(root));