Java Script Object Notation

JSON (JavaScript Object Notation) is a lightweight data-interchange format, with language bindings for CeeLanguage, CeeSharp, JavaLanguage, JavaScript, ObjectiveCaml, PhpLanguage, SmlLanguage, RubyLanguage. It basically uses Python's syntax for dictionaries and lists, and so it works in PythonLanguage, too (but watch out for true, false, and null).

Also watch out for cyclical structures. Some tuning of the json.parse() method (see below) is needed.

JSON-RPC is a simple RemoteProcedureCall protocol similar to XmlRpc although it uses the lightweight JSON format instead of XML. Lightweight JSON-RPC clients have been implemented in JavaScript, making it possible to call remote methods from a WebBrowser without reloading the page. Think 'Google Suggest' (and AjaxWebApplications).

The definitive reference to JSON is http://www.json.org/

Pros:

Cons:

JSON is very close in syntax to a subset of YamlAintMarkupLanguage, with almost the same InfoSet.
JSON-LD (see http://json-ld.org/ ) is JSON for linking data.

See also http://www.w3.org/TR/json-ld-syntax/
For illustration, here is a naive PythonLanguage class for handling JSON data. Because according to the grammar, a JSON structure is always enclosed by curly braces, it is essentially a dict.

 from pprint import pprint
 from StringIO import StringIO

true, false = True, False null = None

class JSON(dict): """Naive JSON class.

A safer __init__ method would parse the JSON string rather than do eval. A smarter __str__ method would perform more careful matches of True, False, and None. Per the JSON spec, the __str__ method should output string values in double quotes, but this outputs single quotes. Also, a correct implementation would use Unicode. """

def __init__(self, arg={}): """JSON(dictOrString)""" try: e = eval(arg) self.update(e) except TypeError: self.update(arg)

def __str__(self): """return pretty print of JSON object""" stream = StringIO() pprint(dict(self), stream) s = stream.getvalue().strip() s = s.replace('True', 'true') s = s.replace('False', 'false') s = s.replace('None', 'null') return s

obj = {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}, {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"}, {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"} ], "foo": true, "bar": null }

print JSON() print JSON(obj) json = JSON(str(obj)) for binding in json['bindings']: print binding['method']
outputs...

 {}
 {'bar': null,
  'bindings': [{'ircEvent': 'PRIVMSG',
                'method': 'newURI',
                'regex': '^http://.*'},
               {'ircEvent': 'PRIVMSG',
                'method': 'deleteURI',
                'regex': '^delete.*'},
               {'ircEvent': 'PRIVMSG',
                'method': 'randomURI',
                'regex': '^random.*'}],
  'foo': true}
 newURI
 deleteURI
 randomURI
See the JSON home page for a link to a much smarter PythonLanguage module.

Question: How do you efficiently decode JSON in JavaScript without potentially running arbitrary code? Just eval'ing a string would let a sender create or call functions. Does JavaScript have the concept of safe interpreters? Or must a parser for JSON be written in JavaScript.

Answer: Use json.parse(text), as follows (from http://www.json.org):

 /*
    Parse a JSON text, producing a JavaScript value.
    It returns false if there is a syntax error.
 */
    parse: function (text) {
        try {
            return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                    text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
                eval('(' + text + ')');
        } catch (e) {
            return false;
        }
    }
 };


See AlternativesToXml. See also CubicWeb.
CategoryInformation CategorySemanticWeb

EditText of this page (last edited May 11, 2013) or FindPage with title or text search