6

What is the best way to make a JSON object in jQuery (without using a parser or AJAX)?

var JSONobj = new JSON({'a':'b'})
Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
aaltruista
  • 61
  • 2
  • [From ECMAScript 5th](http://ecma262-5.com/ELS5_HTML.htm#Section_15.12): *"The JSON object does not have a [[Construct]] internal property; it is not possible to use the JSON object as a constructor with the new operator."* – user113716 Jun 19 '11 at 21:40

4 Answers4

6

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. 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...These properties make JSON an ideal data-interchange language.

source

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.*"}
    ]
};

source

However to parse JSON from an external source or serialize JSON objects from your own code, you'll need a library such as JSON-js as Javascript/ECMAScript doesn't currently support this, although:

It is expected that native JSON support will be included in the next ECMAScript standard.

Andy
  • 17,423
  • 9
  • 52
  • 69
  • 2
    ECMAScript 5th ed. supports JSON natively. See section [15.12](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf) - JSON Object. – Anurag Jun 19 '11 at 20:56
4

JSON is the serialized representation of an object. It is just a string. To create a JSON representation out of a JavaScript object, use JSON.stringify.

var myObject = { hello: "world", foo: [ "bar", "baz", 42 ] };

JSON.stringify(myObject); // "{"hello":"world","foo":["bar","baz",42]}"
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • Be aware that not all browsers support JSON.stringify. – Greg Jun 19 '11 at 21:16
  • @Greg - most modern browsers do [support](http://stackoverflow.com/questions/891299/browser-native-json-support-window-json) it natively, and for the ones that don't, easy to [add](https://gist.github.com/443002) it yourselves. – Anurag Jun 19 '11 at 21:22
3

You should be able to just use an object literal syntax:

var JSONobj = {'a':'b'};
Andy Hume
  • 40,474
  • 10
  • 47
  • 58
1

I'm not sure what you're trying to do, but if you just want to create an object, create it...

var myObj = { a : "b" };
James Montagne
  • 77,516
  • 14
  • 110
  • 130