cheetsheetz/JSON.md

3.0 KiB

JSON Cheat Sheet

Table of Contents

  1. Introduction to JSON
  2. JSON Data Types 2.1 String 2.2 Number 2.3 Boolean 2.4 Array 2.5 Object 2.6 Null
  3. JSON Syntax
  4. JSON Example
  5. Reading and Writing JSON in Python
  6. Accessing JSON Data in JavaScript
  7. Accessing JSON Data in PHP
{
    "name": "JSON Cheat Sheet",
    "version": "1.1",
    "author": "OpenAI",
    "topics": ["JSON", "Data Types", "Syntax", "Example"]
}

1. Introduction to JSON

  • JSON stands for JavaScript Object Notation.
  • It is a lightweight data interchange format.
  • JSON is language-independent and easy for humans to read and write.
  • Commonly used for data exchange between a server and web application, as well as for configuration files.

2. JSON Data Types

2.1 String

  • Represents a sequence of characters.
  • Enclosed in double quotes.
  • Example: "Hello, World!"

2.2 Number

  • Represents a numerical value (integer or floating-point).
  • Example: 42 or 3.14

2.3 Boolean

  • Represents a logical value, either true or false.

2.4 Array

  • Ordered list of values.
  • Enclosed in square brackets [].
  • Example: [1, 2, "three", true]

2.5 Object

  • Unordered collection of key-value pairs.
  • Enclosed in curly braces {}.
  • Example: {"name": "John", "age": 30, "city": "New York"}

2.6 Null

  • Represents a null or empty value.

3. JSON Syntax

  • Data is represented in key-value pairs.
  • Keys are always strings and followed by a colon.
  • Pairs are separated by commas.
  • Objects are enclosed in curly braces {}.
  • Arrays are enclosed in square brackets [].

4. JSON Example

{
    "name": "John Doe",
    "age": 25,
    "isStudent": false,
    "courses": ["Math", "History", "Science"],
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "zip": "12345"
    },
    "contact": null
}

5. Reading and Writing JSON in Python

import json

# Reading JSON from a file
with open('data.json', 'r') as json_file:
    data = json.load(json_file)
    print(data)

# Writing Python data to a JSON file
data_to_write = {"name": "Jane Doe", "age": 30, "city": "AnotherTown"}

with open('output.json', 'w') as json_file:
    json.dump(data_to_write, json_file, indent=4)

6. Accessing JSON Data in JavaScript

// Assuming jsonString is a JSON string
var jsonData = JSON.parse(jsonString);

// Accessing data
console.log(jsonData.name); // Outputs: John Doe
console.log(jsonData.address.city); // Outputs: Anytown

7. Accessing JSON Data in PHP

// Assuming jsonString is a JSON string
$jsonData = json_decode($jsonString, true);

// Accessing data
echo $jsonData['name']; // Outputs: John Doe
echo $jsonData['address']['city']; // Outputs: Anytown