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'}) 
1
  • From ECMAScript 5th: "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." Commented Jun 19, 2011 at 21:40

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ECMAScript 5th ed. supports JSON natively. See section 15.12 - JSON Object.
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]}" 

2 Comments

Be aware that not all browsers support JSON.stringify.
@Greg - most modern browsers do support it natively, and for the ones that don't, easy to add it yourselves.
3

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

var JSONobj = {'a':'b'}; 

1 Comment

I think he really wants a JSON serialization of an existing JavaScript object.
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" }; 

1 Comment

In your example you created a javascript object but it is not a JSON.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.