Database.json Access
: Always include a unique id for each post so you can find or delete it later.
import json new_post = {"id": 1, "title": "Hello from Python", "content": "Writing to JSON is easy!"} # Load existing data with open('database.json', 'r+') as file: db = json.load(file) db['posts'].append(new_post) # Seek to start and overwrite file.seek(0) json.dump(db, file, indent=2) Use code with caution. Copied to clipboard Best Practices for database.json
In your terminal, run: npx json-server --watch database.json database.json
Create a database.json with an initial structure: { "posts": [] } Use code with caution. Copied to clipboard
: JSON requires double quotes for keys and string values; single quotes will cause an error. : Always include a unique id for each
: For larger projects, consider libraries like lowdb , which provide a safer API for interacting with local JSON files. typicode/lowdb: Simple and fast JSON database - GitHub
fetch('http://localhost:3000/posts', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ title: "My First Post", content: "This is some data saved to database.json!" }), }) .then(response => response.json()) .then(data => console.log('Success:', data)); Use code with caution. Copied to clipboard 2. Using Node.js (Direct File Writing) Copied to clipboard : JSON requires double quotes
You can now send a POST request to http://localhost:3000/posts using fetch in JavaScript: javascript














