JSON (JavaScript Object Notation): Concepts, Methods, Examples and Security Threats

22 July, 2008 at 12:41 8 comments

JSON logoJSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangable with programming languages also be based on these structures.

In JSON, they take on these forms:

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

A string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.

JavaScript is a general purpose programming language that was introduced as the page scripting language for Netscape Navigator. It is still widely believed to be a subset of Java, but it is not. It is a Scheme-like language with C-like syntax and soft objects. JavaScript was standardized in the ECMAScript Language Specification, Third Edition.

JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.

var myJSONObject = {"bindings": [
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
        {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
        {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}

In this example, an object is created containing a single member "bindings", which contains an array containing three objects, each containing "ircEvent", "method", and "regex" members.

Members can be retrieved using dot or subscript operators.

myJSONObject.bindings[0].method    // "newURI"

To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript’s syntax.

var myObject = eval('(' + myJSONtext + ')');

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.

To defend against this, a JSON parser should be used. A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

var myObject = JSON.parse(myJSONtext, reviver);

The optional reviver parameter is a function that will be called for every key and value at every level of the final result. Each value will be replaced by the result of the reviver function. This can be used to reform generic objects into instances of pseudoclasses, or to transform date strings into Date objects.

myData = JSON.parse(text, function (key, value) {
    var type;
    if (value && typeof value === 'object') {
        type = value.type;
        if (typeof type === 'string' && typeof window[type] === 'function') {
            return new (window[type])(value);
    return value;

A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.

var myJSONText = JSON.stringify(myObject, replacer);

If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation.

The stringifier method can take an optional array of strings. These strings are used to select the properties that will be included in the JSON text.

The stringifier method can take an optional replacer function. It will be called after the toJSON method (if there is one) on each of the values in the structure. It will be passed each key and value as parameters, and this will be bound to object holding the key. The value returned will be stringified.

If you do not provide an array or replacer function, then an optional replacer function will be provided for you that omits inherited properties. If you want all inherited properties, you can provide a simple replacer function:

var myJSONText = JSON.stringify(myObject, function (key, value) {
    return value;

Values that do not have a representation in JSON (such as functions and undefined) are excluded.

Nonfinite numbers are replaced with null. To substitute other values, you could use a replacer function like this:

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    return value;

Giving a corresponding revivor to JSON.parse can undo that.

What do you mean? A function is an object too?

This might be unusual to developers that never thought about that, but in JS a function is also an object. You can pass a function around as an argument to another function just like you can pass a string, for example. This is extensively used and very handy.

Take a look at this example. We will pass functions to another function that will use them.

var myDog = {
	bark: function(){

var myCat = {
	meow: function(){
		alert('I am a lazy cat. I will not meow for you.');

function annoyThePet(petFunction){
	//let's see what the pet can do

//annoy the dog:
//annoy the cat:

Note that we pass myDog.bark and myCat.meow without appending parenthesis “()” to them. If we did that we would not be passing the function, rather we would be calling the method and passing the return value, undefined in both cases here.

If you want to make my lazy cat start barking, you can easily do this:

myCat.meow = myDog.bark;
myCat.meow(); //alerts 'Woof!'


  • php-json is an extremely fast PHP C extension for JSON (JavaScript Object Notation) serialisation. It conforms to the JSON specification.
  • Zend_Json provides convenience methods for serializing native PHP to JSON and decoding JSON to native PHP. For more information on JSON, visit the JSON project site.
  • XML-RPC for PHP. A PHP implementation of the XML-RPC web RPC protocol. Extra modules provide support for the JSON and JSONRPC protocols. A javascript version of the library is also available.


  • SOJO stands for Simplify your Old Java Objects or, in noun form, Simplified Old Java Objects.
    The intention for this project is a Java framework, that convert JavaBeans in a simplified representation. So it is easy and uniform to handle and control the access to JavaBeans properties.
  • google-gson is a Java library that can be used to convert Java Objects into its JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
  • SON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans.
    It is based on the work by Douglas Crockford in http://www.json.org/java .

JASON and C++

  • TinyJSON – a minimalistic yet powerful JSON parser that makes extensive use of several Boost classes, such as the great Boost.Spirit parsing framework, Boost.Any, and Boost.Smart_Ptr.
  • jsoncpp is an implementation of a JSON (http://json.org) reader and writer in C++. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.
  • JOST, also uses Boost Spirit! There are, however, considerable differences between JSON Spirit and JOST in both design and implementation.

JASON and Security Threats

Never send JSON via Querystring

Sending JSON over a querystring would typically cause a cross-site scripting vulnerability as JSON strings are eval’d by the Javascript. JSON content should always come from a trusted source as the content body.

Always return JSON with an Object on the outside

Always have the outside primitive be an object for JSON strings. This will help mitigate so called “JavaScript Hijacking” as talked about in this paper.


[{"object": "inside an array"}]

Not exploitable:

{"object": "not inside an array"}

Also not exploitable:

{"result": [{"object": "inside an array"}]}

Never Trust The Browser

The browser cannot and will not protect your secrets, so never send it your secret sauce. Keep your critical processes on the server. If you are doing input validation in the browser, it is for the user’s convenience. Everything that the browser sends to the server must be validated.

Keep Data Clean

JSON is a subset of JavaScript, which makes it especially easy to use in web applications. The eval function can take a text from XMLHttpRequest and instantly inflate it into a useful data structure. Be aware however that the eval function is extremely unsafe. If there is the slightest chance that the server is not encoding the JSON correctly, then use the parseJSON method instead. The parseJSON method uses a regular expression to ensure that there is nothing dangerous in the text. The next edition of JavaScript will have parseJSON built in. For now, you can get parseJSON at http://www.JSON.org/json.js.

On the server side, always use good JSON encoders and decoders.

Script Tags

Another use of script tags is to deliver JSON data from different sites. There is absolutely no protection against the case where the different site sends dangerous scripts instead of benign JSON data. Hopefully, some day soon, browsers will offer safe cross-site data transport. Script tags are too dangerous to use for data transport.

Script tags can also be used to deliver Ajax Libraries. Do not load libraries from other sites unless you have a high level of trust in the vendors.


Any time you are transmitting confidential information or requests for confidential information, use SSL. It provides link encryption so that your secrets are not revealed in transit.






Bookmark and Share


Entry filed under: C++, Java, JavaScript, JSON, PHP, Security. Tags: , , , , , .

Single sign-on (SSO): Concepts, Methods and Frameworks JRuby – Java and Ruby: Concepts, Methods and Examples

8 Comments Add your own

  • 1. violet_alex  |  28 July, 2008 at 14:59

    ty very much for this tutorial it was VERY useful. I am working at a site’s admin and was having problems with JSON syntax which I send as a a response from ajax call. your tutorial helped me very much, ty again.

  • 2. Raj  |  11 August, 2008 at 12:22

    How I apply This code in my web page.

  • 3. A Mohamad  |  30 September, 2010 at 12:15

    useful article

  • 4. sambit Mohanty  |  5 April, 2011 at 11:34

    Nie one keep updating..

  • 5. flash  |  5 August, 2011 at 12:45

    I have put together a little JSON sample that iterates over a JavaScript object and posts the property values to a cross domain server that is hosts by a DotNet.aspx page that then converts a C# object to a JSON string that is then posted back to the browser and converted back to a JavaScript object without having to use Window.Eval()

    The resultant JavaScript object is then finally past back to a call-back function that is ready to uses and the code does not need 3rd party libraries, works in net framework 2.0 and upwards and has been tested with IE6-IE9, Firefox plus it’s lightweight.

    Click my name for full details

  • 6. VG  |  24 August, 2011 at 09:50

    This content has been exactly copied from other resources.
    Please post something new which originally encountered by you.

  • 7. jpasswordfield  |  4 April, 2013 at 07:38

    Someone essentially help to make severely posts I would
    state. That is the very first time I frequented your website page and
    thus far? I amazed with the research you made to make this actual publish incredible.

    Wonderful process!

  • 8. Securely using JSON | Stay Educated  |  11 February, 2014 at 14:14

    […] Any time you are transmitting confidential information or requests for confidential information, use SSL. It provides link encryption so that your secrets are not revealed in transit. Source: https://mauriziostorani.wordpress.com/2008/07/22/json-javascript-object-notation-concepts-methods-exa… […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed

IT Passion’s Store



Get the Source
OSGi supporter
JUG Milano

Upcoming Events


Blog Stats

  • 328,400 hits

My PageRank

What's My Google PageRank?

%d bloggers like this: