Convert JS object to JSON string

后端 未结 27 2487
庸人自扰
庸人自扰 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:22

    For debugging in Node JS you can use util.inspect(). It works better with circular references.

    var util = require('util');
    var j = {name: "binchen"};
    console.log(util.inspect(j));
    
    0 讨论(0)
  • 2020-11-22 01:24

    JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string.

    The conversion is an Object to String

    JSON.parse turns a string of JSON text into a Javascript object.

    The conversion is a String to Object

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

    to make it a JSON String following could be used.

    JSON.stringify({"key":"value"});
    
    JSON.stringify({"name":"binchen"});
    

    For more info you can refer to this link below.

    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

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

    If you're using AngularJS, the 'json' filter should do it:

    <span>{{someObject | json}}</span>
    
    0 讨论(0)
  • 2020-11-22 01:30

    JSON.stringify(j, null, 4) would give you beautified JSON in case you need beautification also

    The second parameter is replacer. It can be used as Filter where you can filter out certain key values when stringifying. If set to null it will return all key value pairs

    0 讨论(0)
  • 2020-11-22 01:30
    So in order to convert a js object to JSON String: 
    

    The simple syntax for converting an object to a string is

    JSON.stringify(value)
    

    The full syntax is: JSON.stringify(value[, replacer[, space]])

    Let’s see some simple examples. Note that the whole string gets double quotes and all the data in the string gets escaped if needed.

    JSON.stringify("foo bar"); // ""foo bar""
    JSON.stringify(["foo", "bar"]); // "["foo","bar"]"
    JSON.stringify({}); // '{}'
    JSON.stringify({'foo':true, 'baz':false}); /* " 
    {"foo":true,"baz":false}" */
    
    
    
    const obj = { "property1":"value1", "property2":"value2"};
    const JSON_response = JSON.stringify(obj);
    console.log(JSON_response);/*"{ "property1":"value1", 
    "property2":"value2"}"*/
    
    0 讨论(0)
  • 2020-11-22 01:31

    In angularJS

    angular.toJson(obj, pretty);
    

    obj: Input to be serialized into JSON.

    pretty(optional):
    If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.

    (default: 2)

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