- JSON .stringify()
- Stringify a JavaScript Object
- Example
- Stringify a JavaScript Array
- Example
- Storing Data
- Example
- Exceptions
- Stringify Dates
- Example
- Stringify Functions
- Example
- Example
- Javascript set to json
- # Table of Contents
- # Convert a Set to JSON in JavaScript
- # Convert a Set to JSON using spread syntax (. )
- # Convert a JSON string to a Set in JavaScript
- # Convert an Object with Set values to JSON
- JavaScript JSON methods, toJSON
- JSON.stringify
- Excluding and Transforming: replacer
- Formatting:space
- Custom “toJSON”
- JSON.parse
- Summary
JSON .stringify()
A common use of JSON is to exchange data to/from a web server.
When sending data to a web server, the data has to be a string.
Convert a JavaScript object into a string with JSON.stringify() .
Stringify a JavaScript Object
Imagine we have this object in JavaScript:
Use the JavaScript function JSON.stringify() to convert it into a string.
The result will be a string following the JSON notation.
myJSON is now a string, and ready to be sent to a server:
Example
You will learn how to send JSON to a server in the next chapters.
Stringify a JavaScript Array
It is also possible to stringify JavaScript arrays:
Imagine we have this array in JavaScript:
Use the JavaScript function JSON.stringify() to convert it into a string.
The result will be a string following the JSON notation.
myJSON is now a string, and ready to be sent to a server:
Example
You will learn how to send a JSON string to a server in the next chapters.
Storing Data
When storing data, the data has to be a certain format, and regardless of where you choose to store it, text is always one of the legal formats.
JSON makes it possible to store JavaScript objects as text.
Example
Storing data in local storage
// Storing data:
const myObj = ;
const myJSON = JSON.stringify(myObj);
localStorage.setItem(«testJSON», myJSON);
// Retrieving data:
let text = localStorage.getItem(«testJSON»);
let obj = JSON.parse(text);
document.getElementById(«demo»).innerHTML = obj.name;
Exceptions
Stringify Dates
In JSON, date objects are not allowed. The JSON.stringify() function will convert any dates into strings.
Example
You can convert the string back into a date object at the receiver.
Stringify Functions
In JSON, functions are not allowed as object values.
The JSON.stringify() function will remove any functions from a JavaScript object, both the key and the value:
Example
This can be omitted if you convert your functions into strings before running the JSON.stringify() function.
Example
If you send functions using JSON, the functions will lose their scope, and the receiver would have to use eval() to convert them back into functions.
Javascript set to json
Last updated: Jan 7, 2023
Reading time · 3 min
# Table of Contents
# Convert a Set to JSON in JavaScript
To convert a Set to JSON:
- Use the Array.from() method to convert the Set to an array.
- Use the JSON.stringify() method to convert the array to JSON.
Copied!const set1 = new Set(['a', 'b', 'c']); const json = JSON.stringify(Array.from(set1)); console.log(json); // 👉️ '["a", "b", "c"]' console.log(typeof json); // 👉️ "string"
The Array.from method creates a new, shallow-copied array from the provided iterable.
Copied!const set1 = new Set(['a', 'b', 'c']); console.log(Array.from(set1)); // 👉️ ['a', 'b', 'c']
We had to convert the Set to an array because Set objects don’t have native support for serialization or parsing.
The last step is to use the JSON.stringify() method to convert the array to JSON.
Copied!const set1 = new Set(['a', 'b', 'c']); const json = JSON.stringify(Array.from(set1)); console.log(json); // 👉️ '["a", "b", "c"]'
The JSON.stringify method converts a JavaScript value to a JSON string.
If you have to do this often, define a reusable function.
Copied!function setToJSON(set) return JSON.stringify(Array.from(set)); > const set1 = new Set(['a', 'b', 'c']); // 👇️ '["a","b","c"]' console.log(setToJSON(set1));
The setToJSON function takes a Set object as a parameter, converts it to JSON and returns the result.
# Convert a Set to JSON using spread syntax (. )
This is a two-step process:
- Use the spread syntax (. ) to convert the Set to an array.
- Use the JSON.stringify() method to convert the array to JSON.
Copied!const set1 = new Set(['a', 'b', 'c']); const json = JSON.stringify([. set1]); console.log(json); // 👉️ '["a", "b", "c"]'
We used the spread syntax (. ) to unpack the values of the Set into an array.
This is equivalent to using the Array.from method, however, in some scenarios the spread syntax (. ) doesn’t play nice with TypeScript.
You can define a reusable function if you have to do this often.
Copied!function setToJSON(set) return JSON.stringify([. set]); > const set1 = new Set(['a', 'b', 'c']); // 👇️ '["a","b","c"]' console.log(setToJSON(set1));
# Convert a JSON string to a Set in JavaScript
If you need to convert the JSON string to a Set , you have to:
- Use the JSON.parse() method to parse the JSON string to an array.
- Pass the array to the Set() constructor.
Copied!const set1 = new Set(['a', 'b', 'c']); const json1 = JSON.stringify(Array.from(set1)); console.log(json1); // 👉️ '["a", "b", "c"]' // ✅ Parse back to Set const parsed = new Set(JSON.parse(json1)); console.log(parsed); // 👉️
The Set constructor takes an iterable, such as an array, as a parameter, so we can pass it the result of calling the JSON.parse() method.
The JSON.parse method parses a JSON string into a JavaScript value.
# Convert an Object with Set values to JSON
If you need to convert an object with Set values to JSON, pass a replacer function to the JSON.stringify() method.
Copied!const obj = numbers: new Set([1, 2]), colors: new Set(['red', 'green']), >; const json = JSON.stringify(obj, (_key, value) => return value instanceof Set ? [. value] : value; >); // 👇️ console.log(json);
The replacer function is used to alter the behavior of the stringification process.
The function gets called with each key and value of the object.
On each iteration, we check if the current value is a Set object and if it is, we convert it to an array using the spread syntax (. ).
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
JavaScript JSON methods, toJSON
The JavaScript Object Notation (JSON) is a notable format for representing objects and values. Initially, this format was created for JavaScript, but several languages also include libraries for handling it. Hence, it is easier to use JSON for data exchange in case the client uses JavaScript, and the server is written on PHP, Ruby, Java, and more.
In general, JavaScript provides two methods of converting: JSON.stringify and JSON.parse . You can use the first one for converting objects into JSON and the second one- for converting JSON back into an object.
JSON.stringify
Let’s consider the following example of the JSON.stringify usage:
JSON stringify in javascript
Please, take into account that a JSON-encoded object differs from the object literal. The main differences are as follows:
- Double quotes are used by the string. There shouldn’t be any single quotes or backticks in JSON . For example, ‘W3Docs’ becomes «W3Docs».
- Double quotes should be used for object property names, as well. It’s mandatory. For example, booksCount : 4 will become «booksCount»: 4.
You can apply the JSON.stringify method to primitives, too. It supports the following data types:
JSON stringify in javascript
// a JSON number is an ordinary number console.log(JSON.stringify(10)) // 10 // a JSON string is a double-quoted string console.log(JSON.stringify([1, 2, 3])); // [1,2,3] console.log(JSON.stringify(false)); // false console.log(JSON.stringify(‘W3Docs’)) // «W3Docs»
Note that JSON.stringify skips several JavaScript-specific objects, such as function properties (methods), symbolic properties, and properties storing undefined .
Let’s check out the following case:
JSON stringify in javascript
let site = < welcome() < // ignore console.log("Welcome"); >, [Symbol(«id»)]: 10, // ignore someProperty: undefined // ignore >; console.log(JSON.stringify(site)); // <> — empty object
The best thing about it is that the nested objects are automatically supported and converted.
JSON stringify with nested objects javascript
But, there is an essential limitation as well: you must not use circular references.
Javascript json stringify objects not use circular references
let books = < booksCount: 4 >; let site = < name: "W3Docs", booksTitle: ["html", "css", "js", "git"] >; site.tutorial = books; // site references books books.canUse = site; // books references site console.log(JSON.stringify(site)); // Error: Converting circular structure to JSON
Excluding and Transforming: replacer
For JSON.stringify the following full syntax is used:
let json = JSON.stringify(value[, replacer, space])
- the value: a value for encoding;
- the replacer: the array of properties for encoding or a mapping function function(key, value); ;
- the space:amount of space that is used for formatting.
JSON.stringify uses the first argument most of the time. But if you wish to improve your replacement process, you can also use the second argument. If an array of properties is passed to it, only these properties are encoded.
Let’s have a look at the example:
JSON stringify in javascript
let books = < booksCount: 4 >; let site = < name: "W3Docs", booksTitle: [< title: "html" >, < title: "css" >, < title: "js" >, < title: "git" >], tutorial: books // tutorial references books >; books.canUse = site; // books references site console.log(JSON.stringify(site, [‘name’, ‘booksTitle’])); // <"name":"W3Docs","booksTitle":[<>,<>,<>,<>]>
JSON stringify javascript
Now, let’s try to add in the list all the properties, excluding the books.free :
As you can see, everything is serialized, except canUse . You can also notice that the given list looks rather long. Luckily, the replacer function can be called. You can call it for every key , value pair, and the “replaced” value may be returned. You can use it instead of the original value. For ignoring the canUse the undefined is returned in the example below:
JSON stringify in javascript
let books = < booksCount: 4 >; let site = < name: "W3Docs", booksTitle: [< title: "html" >, < title: "css" >, < title: "js" >, < title: "git" >], tutorial: books // site references books >; books.canUse = site; // books references site console.log(JSON.stringify(site, function replacer(key, value) < console.log(`$
Take into account that the replacer function gets any key/value pair along with array items and nested objects.
Formatting:space
As it was already mentioned, JSON.stringify has three arguments. The third one is the number of spaces used for formatting. Commonly, developers use the space argument to reach an excellent output.
The space = 2 orders JavaScript to display the nested objects on various lines with indentation of two spaces inside an object.
JSON stringify javascript
Custom “toJSON”
As a rule, an object can provide the method toJSON for implementing the to-JSON conversion. If it’s available, the JSON.stringify automatically calls it.
JSON stringify javascript
In the case above, the update (1) is transformed into a string. The reason is that all the dates have a built-in toJSON method.
If you add a custom toJSON for the books (2) object, it will look as follows:
toJSON in javascript
JSON.parse
For decoding a JSON-string another method is used, called JSON.parse with the following syntax:
let value = JSON.parse(str, [reviver]);
JSON is somewhat complicated: objects and arrays may include other objects and arrays. But it’s compulsory to obey the format of JSON .
Below, you can find the typical mistakes in hand-written JSON :
let json = `< welcome: "Welcome", // mistake: property name without quotes "site": 'W3Docs', // mistake: single quotes in value (must be double) 'hasAdmin': true // mistake: single quotes in key (must be double) "update": new Date(2000, 2, 3), // mistake: no "new" is allowed, only bare values "books": [1, 2, 3, 4] // here all fine >`;
Also, note that JSON doesn’t allow commenting. In case you add a comment to it, you will make it invalid. There is a unique format JSON , which supports unquoted keys, comments, and more.
Summary
JSON represents a data format with independent standard and libraries for the majority of programming languages. It supports arrays, strings, objects, booleans, numbers, and null .
JavaScript has the methods JSON.stringify for serializing into JSON and JSON.parse for reading from JSON . In case an object has toJSON , you need to call it by JSON.stringify. .