[javascript] Convert JS object to JSON string

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:

'{"name":"binchen"}'

This question is related to javascript json string object

The answer is


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);

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));

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"}"*/

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

<span>{{someObject | json}}</span>

use JSON.stringify(param1, param2, param3);

What is: -

param1 --> value to convert to JSON

param2 --> function to stringify in your own way. Alternatively, it serves as a white list for which objects need to be included in the final JSON.

param3 --> A Number data type which indicates number of whitespaces to add. Max allowed are 10.


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}'

Simply use JSON.stringify(your_variableName) it will convert your JSON object to string and if you want to convert string to object use JSON.parse(your_variableName)


I was having issues with stringify running out of memory and other solutions didnt seem to work (at least I couldn't get them to work) which is when I stumbled on this thread. Thanks to Rohit Kumar I just iterate through my very large JSON object to stop it from crashing

var j = MyObject;
var myObjectStringify = "{\"MyObject\":[";
var last = j.length
var count = 0;
for (x in j) {
    MyObjectStringify += JSON.stringify(j[x]);
    count++;
    if (count < last)
        MyObjectStringify += ",";
}
MyObjectStringify += "]}";

MyObjectStringify would give you your string representaion (just as mentioned other times in this thread) except if you have a large object, this should also work - just make sure you build it to fit your needs - I needed it to have a name than array


One custom defined for this , until we do strange from stringify method

var j={"name":"binchen","class":"awesome"};
var dq='"';
var json="{";
var last=Object.keys(j).length;
var count=0;
for(x in j)
{
json += dq+x+dq+":"+dq+j[x]+dq;
count++;
if(count<last)
   json +=",";
}
json+="}";
document.write(json);

OUTPUT

{"name":"binchen","class":"awesome"}

LIVE http://jsfiddle.net/mailmerohit5/y78zum6v/


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


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


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

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

For reverse process, you can use JSON.parse() method to convert JSON String to JSON Object.


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 '&nbsp;'),
                    it contains the characters used to indent at each level.

       This method produces a JSON text from a JavaScript value.

The existing JSON replacements where too much for me, so I wrote my own function. This seems to work, but I might have missed several edge cases (that don't occur in my project). And will probably not work for any pre-existing objects, only for self-made data.

function simpleJSONstringify(obj) {
    var prop, str, val,
        isArray = obj instanceof Array;

    if (typeof obj !== "object") return false;

    str = isArray ? "[" : "{";

    function quote(str) {
        if (typeof str !== "string") str = str.toString();
        return str.match(/^\".*\"$/) ? str : '"' + str.replace(/"/g, '\\"') + '"'
    }

    for (prop in obj) {
        if (!isArray) {
            // quote property
            str += quote(prop) + ": ";
        }

        // quote value
        val = obj[prop];
        str += typeof val === "object" ? simpleJSONstringify(val) : quote(val);
        str += ", ";
    }

    // Remove last colon, close bracket
    str = str.substr(0, str.length - 2)  + ( isArray ? "]" : "}" );

    return str;
}

Check out updated/better way by Thomas Frank:

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.

Use this,

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

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!!!


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


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)


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();

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


The most popular way is below:

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


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.


Use the JSON.stringify() method:

const stringified = JSON.stringify({})  // pass object you want to convert in string format

you can use native stringify function like this

_x000D_
_x000D_
const j={ "name": "binchen" }_x000D_
_x000D_
/** convert json to string */_x000D_
const jsonString = JSON.stringify(j)_x000D_
_x000D_
console.log(jsonString) // {"name":"binchen"}
_x000D_
_x000D_
_x000D_


Just use JSON.stringify to do such conversion - however remember that fields which have undefined value will not be included into json

_x000D_
_x000D_
var j={"name":"binchen", "remember":undefined, "age": null };_x000D_
_x000D_
var s=JSON.stringify(j);_x000D_
_x000D_
console.log(s);
_x000D_
_x000D_
_x000D_

The field remember 'disappear' from output json


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor