Many times while working with JavaScript objects, we want to convert them into strings so that we can print them, send them over the network, or store them in a file. This can be done using the toString() method, but the output is not very readable.
Consider the following example:
var o = {a:1, b:2} console.log(o) console.log('Item: ' + o)
This will output:
Object { a=1, b=2} // very nice readable output :) Item: [object Object] // no idea what's inside :(
As you can see, the object is displayed as [object Object], which is not very informative.
To get a more readable string representation of the object, we can use the JSON.stringify() method. This method converts the object to a JSON string, which is a human-readable representation of the object.
Here is the code using JSON.stringify():
var obj = { name: 'myObj' }; JSON.stringify(obj);
This will output the following string:
"{name: 'myObj'}"
Now the string representation of the object is much more readable.
JSON.stringify() is supported by all modern browsers. However, if you are supporting older browsers, you may need to include a JS version of JSON.stringify().
The above is the detailed content of How Can I Convert a JavaScript Object to a Readable String?. For more information, please follow other related articles on the PHP Chinese website!