Reading JSON Back

The reverse trip is parsing: taking JSON text and turning it back into a real dictionary or object you can index into.

JSON text to data

PYTHON

import json

text = '{"name": "Ama", "hours": 95}'
record = json.loads(text)

print(record["name"])

JAVASCRIPT

const text = '{"name": "Ama", "hours": 95}';
const record = JSON.parse(text);

console.log(record.name);
Compare → Python's loads means load-from-string. JavaScript's is JSON.parse. Both hand back live data. Note that JSON always requires double quotes around keys and string values, single quotes are invalid JSON.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Add a third book to the JSON text, then print the title of the last book.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

✦ Round trip

dumps then loads (or stringify then parse) should give you back what you started with. If it does not, something in your data was not JSON-friendly. That round trip is the quickest way to test whether data can safely be saved or sent.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Reading and Writing Files →
← Back