DeveloperBreeze

Append Data to JSON File


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}'.")

Related Posts

More content you might like

Tutorial
php

Securing Laravel Applications Against Common Vulnerabilities

   $filename = time() . '_' . $file->getClientOriginalName();

Store sensitive files in the storage directory and use a controller to serve them securely.

Nov 16, 2024
Read More
Tutorial
javascript

التعامل مع JSON في JavaScript: قراءة البيانات وكتابتها

عندما تحتاج إلى إرسال البيانات من المتصفح إلى الخادم، يمكنك تحويل الكائنات إلى تنسيق JSON باستخدام الدالة JSON.stringify(). هذه الدالة تأخذ كائنًا وتحوله إلى سلسلة JSON.

const person = {
    name: "أحمد",
    age: 30,
    isMarried: false,
    children: ["سارة", "علي"]
};

const jsonString = JSON.stringify(person);
console.log(jsonString);

Sep 26, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

  • The fetch() method returns a Promise that resolves to the Response object representing the entire HTTP response.
  • We check if the response is successful and then parse it as JSON.
  • Any errors during the request are caught and logged.

In many real-world applications, you'll need to send data to the server using POST requests. Here's how to send form data using the Fetch API.

Sep 18, 2024
Read More
Tutorial
go

Building a RESTful API with Go and Gorilla Mux

   curl -X GET http://localhost:8000/books/b1
   curl -X PUT http://localhost:8000/books/b1 -H "Content-Type: application/json" -d '{"title":"Advanced Go","author":"Jane Smith","year":"2024"}'

Aug 12, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!