Saturday, October 15, 2016

How do you correctly create a JSON formatted string?

Although the rules are simple you could run into problems because of the violation of the rules from those described in the RFC 4627.

For example:

{"company":"Hodentek", "phone":"808-722-6785", "city":"Honolulu"}

is correctly JSON formatted and represent a JSON Object. The object is surrounded by curly brackets({ }).

The above is an example of the structured JSON CLR Object type

JSON admits of another structure, an array as shown here:

["Red", "Blue", "Yellow", "Magenta"]


is a correctly JSON formatted array. The array is surrounded by square brackets([ ])

The above is an example of the structured JSON CLR array type

Here is a JSON formatted version of an XML that I had used in a 2007 post to explain fine points of JSON.

{ "wclass":[
{"student": {"name":"Linda Jones", "legacySkill":"Access, VB 5.0"}},
{"student": {"name":"Adam Davidson", "legacySkill":"Cobol, MainFrame"}},
{"student": {"name":"Charles Boyer", "legacySkill":"HTML, XML"}} ]

I recently noticed that I had committed an error although the code in the post worked quite well when parsed using JavaScript. At that time I had not verified whether it was strictly validated and I had used 'inspection' to write out the JSON looking at the XML.

I recently visited JSON formatting in order to answer a question that came up on http://stackoverflow.com/ and I wanted to check my old code. I found this site which is quite useful for such validation.

https://jsonformatter.curiousconcept.com/

On this site you can check your JSON very easily by just entering your JSON data or a URL reference to it. After typing in, just hit the "Process" button and the page gets updated showing the result. If there are errors the site also shows the errors.


Here is my first iteration:

jsontest_00

Here is the result after processing:


jsontest_001

You can go back to where you typed at the top of the web page, without refreshing the page and make necessary corrections and resubmit by hitting the 'Process' button again. In this way you can arrive at the correct formatting.

This is the correction to my old code:

["wclass",
{"student":{"name":"Linda Jones","legacySkill":"Access, VB 5.0"}
},
{  "student":{"name":"Adam Davidson","legacySkill":"Cobol, MainFrame"}
},
{"student":{"name":"Charles Boyer","legacySkill":"HTML, XML"}
}]


Here is the response that the above is properly validated.


jsontest_031.jpg

This is the error (I should have used a comma(,) instead of a colon(:))  I might have had in my old code:


jsonold.png

There is one more check I will do before I am completely satisfied. I will rerun the JavaScript code to see whether some things have changed.


No comments: