JSON Cheat Sheet

Here’s a cheat sheet for working with JSON (JavaScript Object Notation), a lightweight data-interchange format:

JSON Basics

JSON Structure:

JSON is a collection of key-value pairs, where keys are strings and values can be strings, numbers, objects, arrays, booleans, or null.

Example JSON Object:

{
  "name": "John Doe",
  "age": 30,
  "isStudent": false,
  "city": "New York",
  "skills": ["JavaScript", "Python", "HTML"]
}

JSON Data Types

String:

"name": "John Doe"

Number:

"age": 30

Boolean:

"isStudent": false

Array:

"skills": ["JavaScript", "Python", "HTML"]

Object:

"address": {
  "street": "123 Main St",
  "city": "Cityville"
}

Null:

"optionalField": null

Accessing JSON

Accessing Values:

  • In JavaScript:
let name = jsonObject.name;

JSON in Different Languages

JavaScript (JSON.parse):

let jsonString = '{"name": "John Doe", "age": 30}';
let jsonObject = JSON.parse(jsonString);

JavaScript (JSON.stringify):

let jsonObject = { "name": "John Doe", "age": 30 };
let jsonString = JSON.stringify(jsonObject);

Python (json module):

import json

jsonString = '{"name": "John Doe", "age": 30}'
jsonObject = json.loads(jsonString)

jsonObject = {"name": "John Doe", "age": 30}
jsonString = json.dumps(jsonObject)

Formatting and Beautifying

Format JSON for Readability:

  • Online tools or IDE extensions can help format JSON for better readability.

Common JSON Tools

jq (Command-Line JSON Processor):

  • A lightweight and flexible command-line JSON processor.
  • Example: cat data.json | jq .

JSONLint (Online JSON Validator):

  • Validate and format JSON online.
  • JSONLint

Notes

JSON is commonly used for data exchange between a server and a web application.

JSON is human-readable and easy to parse in various programming languages.

This cheat sheet covers the basics of JSON and how to work with it in different programming languages. JSON is widely used in web development, APIs, and data interchange due to its simplicity and ease of use.