import json
# Define the JSON file to read and write
json_file = 'list.json'
# Read the existing JSON data
try:
with open(json_file, 'r') as file:
json_list = json.load(file)
print("Successfully loaded the JSON file.")
except FileNotFoundError:
print(f"File '{json_file}' not found. Initializing with an empty list.")
json_list = []
except json.JSONDecodeError:
print(f"File '{json_file}' is not a valid JSON file. Initializing with an empty list.")
json_list = []
# New data to add to the JSON
new_entry = {'Name': 'The Good Coder', 'Hobbies': 'Code, Write Code!'}
# Append the new data to the JSON list
json_list.append(new_entry)
print("New entry added to the JSON list.")
# Write the updated list back to the JSON file
with open(json_file, 'w') as file:
json.dump(json_list, file, indent=4)
print(f"Updated JSON data written to '{json_file}'.")
Append Data to JSON File
Related Posts
More content you might like
Securing Laravel Applications Against Common Vulnerabilities
Use Laravel’s sanitize middleware or manually clean inputs before storing or displaying:
use Illuminate\Support\Str;
$cleanInput = Str::clean($request->input('content'));التعامل مع JSON في JavaScript: قراءة البيانات وكتابتها
في JavaScript (في بيئات Node.js)، يمكنك أيضًا كتابة بيانات JSON إلى ملف. أولاً، تحتاج إلى تحويل الكائن إلى JSON باستخدام JSON.stringify()، ثم استخدام الوحدة fs لكتابة البيانات إلى ملف.
const fs = require('fs');
const person = {
name: "أحمد",
age: 30,
isMarried: false,
children: ["سارة", "علي"]
};
const jsonString = JSON.stringify(person, null, 2);
fs.writeFile('person.json', jsonString, (err) => {
if (err) {
console.error('حدث خطأ أثناء الكتابة إلى الملف', err);
} else {
console.log('تم كتابة الملف بنجاح!');
}
});AJAX with JavaScript: A Practical Guide
- We create a new
XMLHttpRequestobject and open a GET request to the JSONPlaceholder API (a fake online REST API). - When the request is successful (status code 200), we parse the JSON data and display it on the page.
The Fetch API is a modern alternative to XMLHttpRequest. It's easier to use, more flexible, and based on Promises, making it simpler to handle asynchronous requests.
Building a RESTful API with Go and Gorilla Mux
func updateBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for index, item := range books {
if item.ID == params["id"] {
books = append(books[:index], books[index+1:]...)
var book Book
_ = json.NewDecoder(r.Body).Decode(&book)
book.ID = params["id"]
books = append(books, book)
json.NewEncoder(w).Encode(book)
return
}
}
json.NewEncoder(w).Encode(books)
}Add the deleteBook function to main.go:
Discussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!