javascript convert object to json
javascriptTo convert an object to a JSON string in JavaScript, you can use the JSON.stringify() function. Here’s an example:
const obj = {
name: 'John',
age: 30,
city: 'New York'
};
const json = JSON.stringify(obj);
console.log(json);
// Output: '{"name":"John","age":30,"city":"New York"}'
You can also specify a replacer function as the second argument to JSON.stringify(), which allows you to modify the value that gets stringified. And you can use the third argument to specify a space to use for pretty-printing the output.
For example:
const json = JSON.stringify(obj, (key, value) => {
if (key === 'age') {
return value + 10;
}
return value;
}, 2);
console.log(json);
// Output:
// {
// "name": "John",
// "age": 40,
// "city": "New York"
// }
This will add 10 to the age property when stringifying the object, and also pretty-print the output with 2 spaces of indentation.
Other Article on Tag javascript
- - Adding and removing content in jQuery
- - Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
- - Can I change the Dojo namespace to something other than dojo
- - Can I prevent user pasting Javascript into Design Mode IFrame
- - dynamically create html element in javascript
- - Find XY of an HTML element with JavaScript
- - How can I upload files asynchronously with jQuery
- - How can you display Typing Speed using Javascript or the jQuery library
- - How do you capture mouse events in firefox
- - How to auto-size an iFrame