How to convert JS Object to JSON

This question already has an answer here:

  • Serializing an object to JSON 3 answers

  • Quite literally, JSON is a stricter format for what is basically the right-hand side of a Javascript variable assignment. It's a text-based encoding of Javascript data:

    var foo = ...json goes here ...;
    

    JSON can be ANY valid Javascript data-only structure. A boolean, an int, a string, even arrays and objects. What JSON ISN'T is a general serialization format. Something like this

    var foo = new Date();
    json = JSON.stringify(foo); // json gets the string "2016-08-26 etc..."
    newfoo = JSON.parse(json);  // newfoo is now a string, NOT a "Date" object.
    

    will not work. The Date object will get serialized to a JSON string, but deserializing the string does NOT give you a Date object again. It'll just be a string.

    JSON can only represent DATA, not CODE. That includes expressions

    var foo = 2; // "2" is valid json
    var foo = 1+1; // invalid - json does not have expressions.
    var foo = {"bar":["baz"]}; // also valid JSON
    var foo = [1,2,3+4]; // fails - 3+4 is an expression
    

    To convert JS data object to JSON , you can use JSON.stringify()

    Exmaple

    Input :-

    var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
    JSON.stringify(person)
    

    Output:

    "{"firstName":"John","lastName":"Doe","age":50,"eyeColor":"blue"}"
    
    链接地址: http://www.djcxy.com/p/46272.html

    上一篇: 我怎样才能在JavaScript / jQuery中建立一个json字符串?

    下一篇: 如何将JS对象转换为JSON