- Human- and machine- readable and writable
- Used for storage and transmission of data
- Language agnostic
- Alternative to XML in AJAX
- JavaScript methods
JSON.stringify
andJSON.parse
- Equivalents in python, Java etc
- Plain text
- Encodes objects, lists, strings, numbers, boolean, null
- Does not encode functions
- Read the language summary
- Subset of object literal notation in JavaScript
- Object keys need to be in (double) quotes
- Set method to
POST
- Set
'Content-Type': 'application/json'
in headers - Use JSON.stringify() to encode body
- See postStuff example
- Note use of httpbin for testing client without a server
- Get JSON from server with res.json
- Or use JSON.parse() on res.text() to make an Array/Object
- Iterate through the response with
- Create/append/update DOM nodes based on result
- Could use template literals to update innerHTML
Add middleware for JSON body parsing
app.use(express.json());
Then access req.body
within a .post
route.
To send JSON jwith express either
- use res.json()
- pass res.send() an Array or Object
- Server-side only (nodejs)
- Convert object to JSON with
JSON.stringify
- Use
writeFileSync
from thefs
module
const fs = require('fs');
let data = JSON.stringify([1, 2, 3]);
fs.writeFileSync('./file.json', data);
- Server-side only (nodejs)
- Could load a file and then use
JSON.parse
- Or simply
const jsonContent = require("./file.json");