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

   use Illuminate\Support\Facades\URL;

   public function boot()
   {
       if (app()->environment('production')) {
           URL::forceScheme('https');
       }
   }

Use a middleware like spatie/laravel-cors to set secure headers:

Nov 16, 2024
Read More
Tutorial
javascript

التعامل مع 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('تم كتابة الملف بنجاح!');
    }
});

Sep 26, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

In this guide, we'll explore how AJAX works, the basics of making AJAX requests using vanilla JavaScript, and some real-world examples to help you implement AJAX in your own projects.

  • Basic knowledge of HTML, CSS, and JavaScript.
  • Familiarity with JSON (JavaScript Object Notation) as a format for exchanging data.

Sep 18, 2024
Read More
Tutorial
go

Building a RESTful API with Go and Gorilla Mux

Add the getBooks function to main.go:

func getBooks(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(books)
}

Aug 12, 2024
Read More

Discussion 0

Please sign in to join the discussion.

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