gpt-4.1-mini-2025-04-14· openai
from WildChat-4.8M
JSON STRINGIFY
Rate quality
Private research annotation
Sign in to add a private research label or note.
- User
JSON STRINGIFY
- Assistant
JSON.stringify()is a JavaScript method that converts a JavaScript object or value to a JSON string. It’s commonly used when you want to serialize data to send it over the network, save it to a file, or store it in a text-based format.
Basic Usage
javascriptconst obj = { name: "Alice", age: 25, active: true }; const jsonString = JSON.stringify(obj); console.log(jsonString); // Output: '{"name":"Alice","age":25,"active":true}'
Syntax
javascriptJSON.stringify(value, replacer, space)- value: The value to convert to a JSON string (usually an object or array).
- replacer (optional): A function or array that controls which properties are included in the output.
- space (optional): A number or string used to insert white space into the output JSON string for readability (e.g., indentation).
Examples
Formatting JSON output with spaces
javascriptconst obj = { name: "Bob", age: 30 }; console.log(JSON.stringify(obj, null, 2)); /* { "name": "Bob", "age": 30 } */Using a replacer function
javascriptconst obj = { name: "Carol", age: 22, password: "secret" }; function replacer(key, value) { if (key === "password") { return undefined; // exclude password from the JSON output } return value; } console.log(JSON.stringify(obj, replacer)); /* {"name":"Carol","age":22} */
Important notes
- Functions,
undefined, and symbols are not serialized. - Date objects are serialized as ISO strings by default.
- Circular references cause
JSON.stringifyto throw an error.
If you want, I can also provide examples for advanced use cases or common pitfalls!
- User
come faccio da stringa ad oggetto?
- Assistant
Per convertire una stringa JSON in un oggetto JavaScript, puoi usare il metodo:
javascriptJSON.parse()
Esempio semplice
javascriptconst jsonString = '{"name":"Alice","age":25}'; const obj = JSON.parse(jsonString); console.log(obj.name); // Output: Alice console.log(obj.age); // Output: 25
Note importanti
- La stringa deve essere in formato JSON valido, altrimenti
JSON.parse()lancerà un errore. - Se non sei sicuro che la stringa sia valida, puoi usare un blocco
try...catchper gestire eventuali errori:
javascriptconst jsonString = '{"name":"Alice","age":25}'; try { const obj = JSON.parse(jsonString); console.log(obj); } catch (e) { console.error('Stringa JSON non valida', e); }
Se vuoi, posso aiutarti anche a capire come validare JSON, oppure come convertire dati più complessi!
- La stringa deve essere in formato JSON valido, altrimenti