JSON & the DOM

Lesson 2 of 6

Parsing and Stringifying JSON

Since JSON is just text, JavaScript needs two built-in functions to move between "JSON as a string" and "JSON as real JavaScript values": JSON.parse and JSON.stringify.

JavaScript

Reading it

  • JSON.parse(text) turns a JSON string into real JavaScript values (objects, arrays, numbers, ...), throws a SyntaxError if the text isn't valid JSON.
  • JSON.stringify(value) turns a JavaScript value into a JSON string.
  • The third argument to stringify, here 2, adds indentation, handy for logging or writing readable files, it has no effect on parsing.
  • Anything JSON.stringify can't represent, functions, undefined values, gets silently dropped from objects (or turned into null inside arrays).
JavaScript

📝 Parse & Stringify Quiz

Passing score: 70%
  1. 1.Which function converts a JSON string into a JavaScript value?

  2. 2.Calling JSON.parse on text that isn't valid JSON throws a ____.

  3. 3.JSON.stringify keeps function properties in the resulting string.