From Text to Objects and Back
To a script, JSON is just text. Before it can work with the data, it has to turn the text into arrays and objects. That's what JSON.parse() does:
const text = `{ "name": "Oslo", "temperature": 5 }`;
console.log(text.temperature);
const city = JSON.parse(text);
console.log(city.temperature + 1);undefined
6The text is in backticks, so that it can contain double quotes. As long as it's text, it has no property temperature, so text.temperature is undefined. JSON.parse() reads the text and returns a real object, whose properties you can read and change. If the text isn't valid JSON, it ends with a SyntaxError.
JSON.stringify() does the opposite: it turns an array or an object into JSON text.
const city = { name: "Rome", temperature: 21 };
console.log(JSON.stringify(city));{"name":"Rome","temperature":21}The result has all the keys in double quotes, as JSON wants, and no spaces. Why would you need that? Data can travel and be stored only as text. When a page sends data to a server, or saves it in the browser (you'll do that later in this lesson), it first turns it into text with JSON.stringify(). When it gets the text back, JSON.parse() makes arrays and objects of it again.
Instructions
Turn forecastText into an array with JSON.parse() and store it in a constant forecast. Then, for each city in forecast, append an li to cityList with text like London: 12 °C.
In sunnyText, show the cities where it's sunny as JSON: make an array of only the sunny cities with filter(), and turn it into text with JSON.stringify(). Look at the result: it's the same data as in forecastText, only without the other cities, the spaces and the line breaks.