简体   繁体   中英

What is the best way to make a JSON object in jQuery?

在jQuery中创建JSON对象的最佳方法是什么(不使用解析器或AJAX)?

var JSONobj = new JSON({'a':'b'})

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.

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]}"

您应该只能使用对象文字语法:

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

我不确定你要做什么,但如果你只是想创建一个对象,那就创建它......

var myObj = { a : "b" };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM