java-script:object-to-string-and-back
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| java-script:object-to-string-and-back [2023/08/11 09:40] – [Object to String] odefta | java-script:object-to-string-and-back [2023/08/11 09:59] (current) – [Notes] odefta | ||
|---|---|---|---|
| Line 35: | Line 35: | ||
| </ | </ | ||
| + | ===== String to Object ===== | ||
| + | **JSON.parse**: | ||
| + | <code javascript> | ||
| + | const str = ' | ||
| + | const obj = JSON.parse(str); | ||
| + | </ | ||
| + | ===== Notes ===== | ||
| + | |||
| + | < | ||
| + | **JSON.stringify** will only include properties that have enumerable **string keys**. It will exclude properties with symbol keys, and it will also **skip** values that are **undefined, | ||
| + | </ | ||
| + | |||
| + | < | ||
| + | **JSON.parse** expects a **valid JSON** string. If the string is not valid JSON, it will throw an error. | ||
| + | </ | ||
| + | |||
| + | < | ||
| + | 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/ | ||
| + | </ | ||
| + | |||
| + | <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, | ||
| + | </ | ||
| + | * **value**: The value to convert to a JSON string. | ||
| + | * **replacer**: | ||
| + | * **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: ' | ||
| + | age: 30, | ||
| + | friends: [' | ||
| + | }; | ||
| + | |||
| + | const jsonString = JSON.stringify(obj, | ||
| + | // 2 is the number of spaces for indentation | ||
| + | </ | ||
| + | |||
| + | Output: | ||
| + | <code javascript> | ||
| + | { | ||
| + | " | ||
| + | " | ||
| + | " | ||
| + | " | ||
| + | " | ||
| + | ] | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | To ski age from being included: | ||
| + | <code javascript> | ||
| + | const obj = { name: ' | ||
| + | const filteredJSON = JSON.stringify(obj, | ||
| + | console.log(filteredJSON); | ||
| + | </ | ||
| + | |||
| + | </ | ||
java-script/object-to-string-and-back.1691746811.txt.gz · Last modified: 2023/08/11 09:40 by odefta
