42

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>')
      });
    });
});
Alex
  • 1,112
  • 4
  • 16
  • 30
  • 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 May 10 '12 at 18:11
  • 1
    I'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 May 10 '12 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 May 10 '12 at 18:30
  • 1
    then 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 May 10 '12 at 18:36
  • @ Felix Kling Yes my TECHNICAL question was whether or not my syntax and structure was correct... – Alex May 10 '12 at 18:39
  • Well, whether your *syntax* is correct can be found out with tools such as http://jsonlint.org/. As for the structure, that is rather conceptional than technical and I would tend to see this as too localized or off topic for this site. – Felix Kling May 10 '12 at 18:50
  • well like I said, I am new to all of this. So maybe I have to figure out the structure on my own, but thanks for the website! I will check it out! The more resources I have the better :-) – Alex May 10 '12 at 18:53
  • Reading that object, made me want to have an `aspirin`. oh and remember "the highest level of sophistication is simplicity". – Val Jul 21 '14 at 14:47
  • Why must the second JSON object put everything into a whole new array? As if only `[{` and `}]` exists... – AmigoJack Jan 04 '23 at 22:17

5 Answers5

25

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

Corkscreewe
  • 2,921
  • 2
  • 22
  • 23
  • Thanks for the tip on eval()! I will make sure to avoid it :) – Alex May 10 '12 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 May 10 '12 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 May 11 '12 at 21:00
18

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");

});

});

Dmitry Zagorulkin
  • 8,370
  • 4
  • 37
  • 60
Alex
  • 1,112
  • 4
  • 16
  • 30
  • 13
    A 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 use `var x = medications.aceInhibitors` instead of `medications[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 Jan 15 '13 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 https://google.github.io/styleguide/jsoncstyleguide.xml?showone=Property_Ordering_Example#Property_Ordering_Example – Ronnie Royston Feb 06 '17 at 02:16
4

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:

  1. There is no good "identifier" string for each object in the array.
  2. There is some clear reason for having an array over a key-value for that entry.
devoid
  • 1,009
  • 10
  • 16
  • Labs is a just placeholder....This is just a rough concept. I know it needs a value. – Alex May 10 '12 at 18:20
0

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.

gkaykck
  • 2,347
  • 10
  • 35
  • 52
  • I don't know what this means "use libraries to generate the code you needed from an object." Could you give an example? – Alex May 10 '12 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 May 10 '12 at 18:24
  • 1
    create 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; http://www.itnewb.com/tutorial/Introduction-to-JSON-and-PHP/page3 here's an example – gkaykck May 10 '12 at 18:24
  • 9
    I think that is highly subjective... I find JSON much easier to read than XML. – Felix Kling May 10 '12 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 May 10 '12 at 18:28
  • I agree. I think JSON is incredibly easy to read. XML is out of control. hehe – Alex May 10 '12 at 18:28
  • XML is not that human-friendly as JSON. – Channaveer Hakari Dec 20 '21 at 11:15
0

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
hmota
  • 379
  • 1
  • 4
  • 10