Convert JS object to JSON string

后端 未结 27 2488
庸人自扰
庸人自扰 2020-11-22 00:43

If I defined an object in JS with:

var j={\"name\":\"binchen\"};

How can I convert the object to JSON? The output string should be:

相关标签:
27条回答
  • 2020-11-22 01:36

    if you want to get json properties value in string format use the following way

    var i = {"x":1}
    
    var j = JSON.stringify(i.x);
    
    var k = JSON.stringify(i);
    
    console.log(j);
    
    "1"
    
    console.log(k);
    
    '{"x":1}'
    
    0 讨论(0)
  • 2020-11-22 01:36

    You can use JSON.stringify() method to convert JSON object to String.

    var j={"name":"hello world"};
    JSON.stringify(j);
    

    To convert this string back to json object, you can use JSON.parse() method.

    0 讨论(0)
  • 2020-11-22 01:38

    if you have a json string and it's not wrapped with [] then wrap it up first

    var str = '{"city": "Tampa", "state": "Florida"}, {"city": "Charlotte", "state": "North Carolina"}';
    str = '[' + str + ']';
    var jsonobj = $.parseJSON(str);
    

    OR

    var jsonobj = eval('(' + str + ')');
    console.log(jsonobj);
    
    0 讨论(0)
  • 2020-11-22 01:39

    Check out updated/better way by Thomas Frank:

    • JSON stringify revisited

    Update May 17, 2008: Small sanitizer added to the toObject-method. Now toObject() will not eval() the string if it finds any malicious code in it.For even more security: Don't set the includeFunctions flag to true.

    Douglas Crockford, father of the JSON concept, wrote one of the first stringifiers for JavaScript. Later Steve Yen at Trim Path wrote a nice improved version which I have used for some time. It's my changes to Steve's version that I'd like to share with you. Basically they stemmed from my wish to make the stringifier:

    • handle and restore cyclical references
    • include the JavaScript code for functions/methods (as an option)
    • exclude object members from Object.prototype if needed.
    0 讨论(0)
  • 2020-11-22 01:40

    All current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:

    var j = {
      "name": "binchen"
    };
    console.log(JSON.stringify(j));

    0 讨论(0)
  • 2020-11-22 01:41

    convert str => obj

    const onePlusStr = '[{"brand":"oneplus"},{"model":"7T"}]';

    const onePLusObj = JSON.parse(onePlusStr);

    convert obj => str

    const onePLusObjToStr = JSON.stringify(onePlusStr);

    References of JSON parsing in JS:
    JSON.parse() : click
    JSON.stringify() : click

    0 讨论(0)
提交回复
热议问题