MANUAL

Reading and validating JSON

01 / WHAT IT IS

Data in text form.

JSON is a way of writing data as text so that programmes can read it. You’ll come across it in configuration files such as package.json and composer.json, and in API responses. You don’t need to write JSON, but it helps if you can read it.

01 / An example

{
  "naam": "Mijn app",
  "versie": 2,
  "online": true,
  "talen": ["nl", "en"],
  "eigenaar": {
    "naam": "Jan",
    "stad": "Groningen"
  }
}

02 / How to read it

  1. Between { } is an object: a list of name-value pairs.
  2. The name is to the left of the colon, and the value is to the right.
  3. Text is enclosed in double quotation marks: "My app".
  4. Numbers, ‘true’, ‘false’ and ‘null’ are written without quotation marks.
  5. A list is enclosed within [ ], such as ["nl", "en"].
  6. A value can itself be an object, such as ‘owner’.

02 / THE RULES

Where things often go wrong.

JSON is strict. Just one wrong character and the whole file stops working.

03 / Common mistakes

  1. Comma after the last item. "stad": "Groningen",} is incorrect. There should be no comma after the last item.
  2. Single quotation marks. 'naam' is incorrect. Always use double quotation marks: "naam".
  3. Missing comma. There is always a comma between two items.
  4. Comment. JSON must not contain // or /* */. Some programmes accept them, but standard JSON does not.
  5. Brackets that don’t match. Every { has a }, every [ heeft een ].

04 / What an error message means

Do you see something like Unexpected token or Expected ',' or '}', with a line number? If so, check that line and the one above it. The error is usually just before the point mentioned in the message.

03 / CHECK

Is my JSON correct?

05 / In VS Code

Open the file. Errors are highlighted with a red wavy line. Press Shift + Alt + F (Windows) or Ctrl + Shift + I (Linux) to have VS Code format the indentation neatly.

06 / In the terminal

With Node.js installed:

node -e "JSON.parse(require('fs').readFileSync('package.json','utf8')); console.log('OK')"

Installed with Python:

Windows

python -m json.tool package.json

Linux

python3 -m json.tool package.json

If the file is correct, you’ll see ‘OK’ or the correct content. If there’s an error, you’ll see where it is.

07 / Check online

Do not paste JSON containing passwords, keys or customer data into a website to check it. Use VS Code or the terminal for this instead.

04 / WORKING WITH AI

Ask your assistant.

08 / A task for your AI assistant

"Check that the JSON files in this project are valid. If there is an error, indicate which line it is on and what you would change, and ask for permission before making any changes."

Good to know

Make a commit before you edit a JSON file manually. If anything goes wrong, you can use Git to revert to the previous version.