User Tools

Site Tools


java-script:object-to-string-and-back

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
java-script:object-to-string-and-back [2023/08/11 12:45] odeftajava-script:object-to-string-and-back [2023/08/11 12:59] (current) – [Notes] odefta
Line 55: Line 55:
 <note> <note>
 If you're working with a more complex object structure that includes methods or other non-serializable values, you may need to implement custom serialization/deserialization logic. If you're working with a more complex object structure that includes methods or other non-serializable values, you may need to implement custom serialization/deserialization logic.
 +</note>
 +
 +<note tip>
 +You can format the output of the **JSON.stringify** to be more easy to read or add transformation / filtering.
 +Syntax:
 +<code javascript>
 +JSON.stringify(value, replacer, space)
 +</code>
 +  * **value**: The value to convert to a JSON string.
 +  * **replacer**: Either a function that alters the behavior of the stringification process or an array of String and Number that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. Passing **null** means that the entire object is included, without any changes.
 +  * **space**: A String or Number object that's used to insert **white space** into the output JSON string for readability purposes.
 +
 +Example:
 +<code javascript>
 +const obj = {
 +  name: 'John',
 +  age: 30,
 +  friends: ['Alice', 'Bob']
 +};
 +
 +const jsonString = JSON.stringify(obj, null, 2); 
 +// 2 is the number of spaces for indentation
 +</code>
 +
 +Output:
 +<code javascript>
 +{
 +  "name": "John",
 +  "age": 30,
 +  "friends": [
 +    "Alice",
 +    "Bob"
 +  ]
 +}
 +</code>
 +
 +To ski age from being included:
 +<code javascript>
 +const obj = { name: 'John', age: 30 };
 +const filteredJSON = JSON.stringify(obj, ['name']);
 +console.log(filteredJSON); // '{"name":"John"}'
 +</code>
 +
 </note> </note>
java-script/object-to-string-and-back.1691747103.txt.gz · Last modified: 2023/08/11 12:45 by odefta