Convert JS object to JSON string

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

    Use the stringify function

    var j = {
    "name":"binchen"
    };
    
    var j_json = JSON.stringify(j);
    
    console.log("j in json object format :", j_json);
    

    Happy coding!!!

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

    Woking... Easy to use

    $("form").submit(function(evt){
      evt.preventDefault();
      var formData = $("form").serializeArray(); // Create array of object
      var jsonConvert = JSON.stringify(formData);  // Convert to json
    });
    

    Thanks

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

    Very easy to use method, but don't use it in release (because of possible compatibility problems).

    Great for testing on your side.

    Object.prototype.toSource()
    
    //Usage:
    obj.toSource();
    
    0 讨论(0)
  • 2020-11-22 01:33

    The most popular way is below:

    var obj = {name: "Martin", age: 30, country: "United States"};   
    // Converting JS object to JSON string
    var json = JSON.stringify(obj);
    console.log(json);

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

    Use the JSON.stringify() method:

    const stringified = JSON.stringify({})  // pass object you want to convert in string format
    
    0 讨论(0)
  • 2020-11-22 01:36

    With JSON.stringify() found in json2.js or native in most modern browsers.

       JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.
    
           replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.
    
           space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or ' '),
                        it contains the characters used to indent at each level.
    
           This method produces a JSON text from a JavaScript value.
    
    0 讨论(0)
提交回复
热议问题