Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Json Stringify in JavaScript

Json Stringify in JavaScript

JSON.stringify() in JavaScript


What is JSON.stringify()?

  • JSON.stringify() is a built-in JavaScript method.

  • It converts a JavaScript object or value into a JSON string.

  • Useful when you want to send data to a server or save it as text.


Syntax

JSON.stringify(value[, replacer[, space]])
  • value: The JavaScript object or value to convert.

  • replacer (optional): A function or array that alters how objects and values are stringified.

  • space (optional): Adds indentation, white space, and line breaks to make the output more readable.


Basic Example

const obj = {  name: "John",  age: 30,  city: "New York"};const jsonString = JSON.stringify(obj);console.log(jsonString);// Output: '{"name":"John","age":30,"city":"New York"}'

Using the replacer Parameter

As a function to filter or transform values:

const obj = {  name: "John",  age: 30,  city: "New York"};const jsonString = JSON.stringify(obj, (key, value) => {  if (typeof value === "number") {    return undefined;  // exclude numbers  }  return value;});console.log(jsonString);// Output: '{"name":"John","city":"New York"}'

As an array to include only specific keys:

const jsonString = JSON.stringify(obj, ["name", "city"]);console.log(jsonString);// Output: '{"name":"John","city":"New York"}'

Using the space Parameter

Makes the JSON output pretty-printed (human-readable):

const jsonString = JSON.stringify(obj, null, 4);console.log(jsonString);/* Output:{    "name": "John",    "age": 30,    "city": "New York"}*/

Summary

ParameterDescriptionExample Usage
valueObject or value to convert to JSON stringJSON.stringify(obj)
replacerFunction or array to filter/transform propertiesJSON.stringify(obj, ['name'])
spaceNumber or string for indentation and formattingJSON.stringify(obj, null, 2)

If you want, I can help you with examples of converting complex objects or handling circular references!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql