Thursday, March 23, 2023
HomePHPConvert JavaScript Object to JSON String

Convert JavaScript Object to JSON String


by Vincy. Final modified on October twenty sixth, 2022.

JSON string conversion on the shopper and server aspect is a vital requirement in information dealing with. Most programming languages include native features for dealing with JSON objects and string information.

The JSON format is a handy manner of structuring, transmitting, or logging hierarchical information. The JSON string is a bundled unit to transmit object properties over the API terminals.

On this tutorial, we’ll see find out how to convert a JavaScript object to a JSON string. The JSON.stringify() of the JS script is used to do that. This can be a fast resolution for changing the given JS object to a JSON.

Fast instance

var jsObject = {
	"title": "Lion",
	"kind": "wild"
};
var jsonString = JSON.stringify(jsObject)
console.log(jsonString);

Output

{"title":"Lion","kind":"wild"}

javascript object to string

About JavaScript JSON.stringify()

The JSON.stringify() methodology accepts 3 parameters to transform JavaScript objects into JSON string. See the syntax and the potential parameters of this JavaScript methodology.

Syntax

JSON.stringify(worth)
JSON.stringify(worth, replacer)
JSON.stringify(worth, replacer, area)

The replacer and area parameters are non-compulsory.

  • worth – The JS object to be transformed to a JSON string.
  • replacer – a  perform or an array of specs to transform JavaScript objects.
  • area – It’s a specification used to format or prettify the output JSON.

The JSON.stringify() methodology can even settle for JavaScript arrays to transform into JSON strings.

The best way to get a formatted JSON string from a JavaScript object

This instance provides the “area” parameter to the JSON.stringify methodology. This parameter helped to format the JSON string as proven within the output under this system.

Once we see the PHP array to JSON conversion instance, it used the PHP bitmask parameter to attain prettyprinting of JSON output.

var jsObject = {
	"title": "Lion",
	"kind": "wild"
};

// that is to transform a JS object to a formatted JSON string
var formattedJSON = JSON.stringify(jsObject, null, 2);
console.log(formattedJSON);

Output

{
  "title": "Lion",
  "kind": "wild"
}

The best way to retailer JSON string to a JavaScript localStorage

The localStorage is a mechanism to have persistent information or state on the shopper aspect. It accepts string information to be saved with a reference of a user-defined key.

On this instance, we used this storage device to maintain the JSON string of cart session information.

This code pushes two data to the cart array. Then, it converts the array into the JSON string to place it into the localStorage.

Be aware: JSON.stringify() can even accepts array to transform right into a JSON string.

Now we have already used this storage mechanism to create a JavaScript persistent purchasing cart.

const cart = {
	cartItem: []
};
cart.cartItem.push({ product: "Watch", amount: 3, unitPrice: 100 });
cart.cartItem.push({ product: "Sensible Cellphone", amount: 5, unitPrice: 600 });

// use case for changing JS object to a JSON string
// convert object to JSON string earlier than storing in native storage
const cartJSONString = JSON.stringify(cart);

localStorage.setItem("cartSession", JSON.stringify(cartJSONString));

// retrieving from native storage
let cartFromStorage = localStorage.getItem("cartSession");
const getCartItemFromSession = JSON.parse(cartFromStorage);

console.log(getCartItemFromSession);

Output

{
   "cartItem":
   [
      {"product":"Watch","quantity":3,"unitPrice":100},
      {"product":"Smart Phone","quantity":5,"unitPrice":600}
   ]
}

How dates within the JavaScript object behave throughout JSON stringify

The JSON.stringify() perform converts the JavaScript Date object into an equal date string as proven within the output.

The code instantiates the JavaScript Date() class to set the present date to a JS object property.

// while you convert a JS object to JSON string, date will get robotically transformed
// to equal string kind
var jsObject = {
	"title": "Lion",
	"kind": "wild",
	right this moment: new Date()
};
const jsonString = JSON.stringify(jsObject);
console.log(jsonString);

Output

{"title":"Lion","kind":"wild","right this moment":"2022-10-23T10:58:55.791Z"}

How JSON stringify converts the JavaScript objects with features

If the JS object accommodates features as a price of a property, the JSON.stringify will omit the perform. Then, it’s going to return nothing for that exact property.

The resultant JSON string could have the remainder of the properties which have legitimate mapping.

// while you convert a JS object to JSON string, 
// features in JS object is eliminated by JSON.stringify 
var jsObject = {
	"title": "Lion",
	"kind": "wild",
	age: perform() {
		return 10;
	}
};
const jsonString = JSON.stringify(jsObject);
console.log(jsonString);

Output

{"title":"Lion","kind":"wild"}

JavaScript toString() limitations over JSON.stringify: 

If the enter JavaScript object accommodates a single or with a predictable construction, toString() can obtain this conversion.

It’s executed by iterating the JS object array and making use of stringification on every iteration. Instance,

let jsonString = {
  'title': 'Lion',
  kind: 'wild',

  toString() {
    return '{title: "${this.title}", age: ${this.kind}}';
  }
};
console.log(jsonString);

However, it’s not an environment friendly manner that has the likelihood of lacking some properties throughout the iteration.

Why and find out how to convert the JSON string right into a JSON object

The JSON string is a snug format throughout information transmission and information logging. Aside from that it should be in a format of an object tree to parse, learn from, and write to the JSON.

The JSON.parse() methodology is used to transform JSON String to a JSON Object. A JSON object will appear to be a JS object solely. See the next comparability between a JS object and a JSON object.

//JavaScript object
const jsObject = {
  'animal-name': 'Lion',
  animalType: 'wild',
  endangered: false
}

//JSON object
{
  "animal-name": "Lion",
  "animalType": "wild",
  "endangered": false
}

Obtain

↑ Again to High

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments