Working with JSON
- JavaScript Object Notation ↗ (JSON) is a lightweight, text-based data format for storing and exchanging data.
- It is easy for humans to read and write, and easy for machines to parse and generate.
- It’s derived from JavaScript but is language-independent, making it widely used across programming languages like Python, Java, C#, and more.
A JSON value can be one of the following types:
- String (e.g.,
"hello") - Number (e.g.,
42,3.14) - Boolean (
true,false) - Object:
{ "key": value1, "key2": valueN } - Array:
[ value1, value2, value3, valueN ] - Null:
null
{ "name": "John Doe", "age": 30, "isStudent": true, "courses": ["Math", "Science", "History"], "address": { "street": "456 Côte-des-Neiges", "city": "Montreal", "state": "QC", "postalCode": "H2X 1Y4" }}json
JavaScript has built-in methods to work with JSON:
- APIs: Most web APIs (e.g., RESTful services) use JSON to send and receive data.
- Configuration Files: Store settings in a structured, readable format.
- Data Storage: Lightweight alternative to databases for small applications.
- Data Interchange: Between systems or components with different technology stacks.
- Lightweight: Minimal syntax, no unnecessary tags or attributes.
- Human-readable: Easy to understand and edit manually.
- Widely supported: Native support in most programming languages via libraries or built-in functions.
- Data Types: Supports strings, numbers, booleans, null, objects, and arrays.
- Hierarchical Structure: Can represent complex data structures with nested objects and arrays.
- Use online tools like JSONLint ↗ or built-in error handling:
- JavaScript:
JSON.parse()throws aSyntaxErrorif invalid.
- JavaScript:
- JavaScript:
const data = { "person": { "name": "Grace", "age": 27 } };console.log(data.person.name); // Output: Gracejavascript
- Use Descriptive Keys: Make keys meaningful (e.g.,
"firstName"instead of"fn"). - Handle Errors: Always wrap JSON parsing in try-catch blocks to handle invalid data.
try {JSON.parse("invalid json");} catch (e) {console.error("Invalid JSON:", e);}javascript
- Pretty Print: Use indentation when saving JSON for readability (e.g.,
JSON.stringify(obj, null, 2)). - Validate Input: Ensure data conforms to expected structure before processing.
- Avoid Circular References: JSON cannot serialize objects with circular references (e.g., an object referencing itself).
- Unexpected End of JSON: Check for missing
}or]. - Invalid Key: Ensure keys are strings with double quotes (e.g.,
"key", notkey). - Encoding Issues: Use UTF-8 encoding for special characters.
Python uses the json module:
- Parsing JSON:
import jsonjson_string = '{"name": "Charlie", "age": 28}'data = json.loads(json_string)print(data["name"]) # Output: Charliepython
- Stringifying:
data = {"name": "Charlie", "age": 28}json_string = json.dumps(data, indent=2) # indent for pretty printingprint(json_string)# Output:# {# "name": "Charlie",# "age": 28# }python
Java uses libraries like org.json or Gson (from Google):
- Using
org.json:import org.json.JSONObject;public class Main {public static void main(String[] args) {String jsonString = "{\"name\": \"David\", \"age\": 35}";JSONObject obj = new JSONObject(jsonString);System.out.println(obj.getString("name")); // Output: David}}java - Creating JSON:
JSONObject obj = new JSONObject();obj.put("name", "David");obj.put("age", 35);System.out.println(obj.toString()); // Output: {"name":"David","age":35}java