How do I encode a JavaScript object as JSON?

后端 未结 2 1860
离开以前
离开以前 2020-11-28 11:23

Is there a good way to encode a JavaScript object as JSON?

I have a list of key value pairs...where the name is from a checkbox, and the value is either true or fals

相关标签:
2条回答
  • 2020-11-28 12:17

    I think you can use JSON.stringify:

    // after your each loop
    JSON.stringify(values);
    
    0 讨论(0)
  • 2020-11-28 12:26

    All major browsers now include native JSON encoding/decoding.

    // To encode an object (This produces a string)
    var json_str = JSON.stringify(myobject); 
    
    // To decode (This produces an object)
    var obj = JSON.parse(json_str);
    

    Note that only valid JSON data will be encoded. For example:

    var obj = {'foo': 1, 'bar': (function (x) { return x; })}
    JSON.stringify(obj) // --> "{\"foo\":1}"
    

    Valid JSON types are: objects, strings, numbers, arrays, true, false, and null.

    Some JSON resources:

    • JSON on Mozilla Developer Network
    • JSON on Wikipedia
    0 讨论(0)
提交回复
热议问题