jsobj["a"]["b"]["e"].append({"f":var3, "g":var4, "h":var5})
jsobj["a"]["b"]["e"].append({"f":var6, "g":var7, "h":var8})
Answer from DrTyrsa on Stack Overflow
🌐
ReqBin
reqbin.com › json › python › uzykkick › json-array-example
Python | What is JSON Array?
Unlike dictionaries, where you can get the value by its key, in a JSON array, the array elements can only be accessed by their index. The following is an example of a JSON array with numbers. Below, you can find a list of JSON arrays with different data types. The Python code was automatically generated for the JSON Array example.
Discussions

append an array to a json python - Stack Overflow
Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I'm dealing with JSON on python3 and I want to append an array ... More on stackoverflow.com
🌐 stackoverflow.com
python - How to add an element to a list? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
Add values to JSON object in Python - Stack Overflow
I'm trying to use the json library in python to load the data and then add fields to the objects in the "accidents" array. More on stackoverflow.com
🌐 stackoverflow.com
Append JSON array with another item using Python - Stack Overflow
I recently migrated to Python and cannot solve quite simple problem (using Django). A model has JSON field (PostgreSQL), lets say, for example, fruits. When updating an instance, I do it like this: More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python.org
discuss.python.org › python help
Unable to append data to Json array object with desired output - Python Help - Discussions on Python.org
January 18, 2023 - I’m tried getting help for same issue on stack-overflow but got no help or replies. I’m re-posting here with the hope that someone can please guide me as I’m unable to push the code to repository due to delay. My code import json import re from http.client import responses import vt import requests with open('/home/asad/Downloads/ssh-log-parser/ok.txt', 'r') as file: file = file.read() pattern = re.compile(r'\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}') ips = pattern.findall(file) unique_ips = lis...
Top answer
1 of 2
6

First, accidents is a dictionary, and you can't write to a dictionary; you just set values in it.

So, what you want is:

for accident in accidents:
    accident['Turn'] = 'right'

The thing you want to write out is the new JSON—after you've finished modifying the data, you can dump it back to a file.

Ideally you do this by writing to a new file, then moving it over the original:

with open('sanfrancisco_crashes_cp.json') as json_file:
    json_data = json.load(json_file)
accidents = json_data['accidents']
for accident in accidents:
    accident['Turn'] = 'right'
with tempfile.NamedTemporaryFile(dir='.', delete=False) as temp_file:
    json.dump(temp_file, json_data)
os.replace(temp_file.name, 'sanfrancisco_crashes_cp.json')

But you can do it in-place if you really want to:

# notice r+, not rw, and notice that we have to keep the file open
# by moving everything into the with statement
with open('sanfrancisco_crashes_cp.json', 'r+') as json_file:
    json_data = json.load(json_file)
    accidents = json_data['accidents']
    for accident in accidents:
        accident['Turn'] = 'right'
    # And we also have to move back to the start of the file to overwrite
    json_file.seek(0, 0)
    json.dump(json_file, json_data)
    json_file.truncate()

If you're wondering why you got the specific error you did:

In Python—unlike many other languages—assignments aren't expressions, they're statements, which have to go on a line all by themselves.

But keyword arguments inside a function call have a very similar syntax. For example, see that tempfile.NamedTemporaryFile(dir='.', delete=False) in my example code above.

So, Python is trying to interpret your accident['Turn'] = 'right' as if it were a keyword argument, with the keyword accident['Turn']. But keywords can only be actual words (well, identifiers), not arbitrary expressions. So its attempt to interpret your code fails, and you get an error saying keyword can't be an expression.

2 of 2
0

I solved with that :

with open('sanfrancisco_crashes_cp.json') as json_file:
        json_data = json.load(json_file)

        accidents = json_data['accidents']
        for accident in accidents:
            accident['Turn'] = 'right'

with open('sanfrancisco_crashes_cp.json', "w") as f:
        json.dump(json_data, f)
Find elsewhere
🌐
Finxter
blog.finxter.com › home › learn python blog › how to append data to a json file in python? [+video]
How to Append Data to a JSON File in Python? [+Video] - Be on the Right Side of Change
June 1, 2022 - Problem Formulation Given a JSON object stored in a file named "your_file.json" such as a list of dictionaries. 💬 How to append data such as a new dictionary to it? # File "your_file.json" (BEFORE) [{"alice": 24, "bob": 27}] # New entry: {"carl": 33} # File "your_file.json" (AFTER) [{"alice": 24, "bob": 27}, {"carl": 33}] Method 1: ... Read more
🌐
GeeksforGeeks
geeksforgeeks.org › append-to-json-file-using-python
Append to JSON file using Python - GeeksforGeeks
March 26, 2024 - The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script.
🌐
Quora
quora.com › How-do-you-add-elements-to-a-JSON-Array
How to add elements to a JSON Array - Quora
Answer (1 of 3): Here’s how you add elements to a JSON array—let’s break it down like you’re sitting around a table with a laptop, trying to figure this out. So, first off, JSON arrays are those square-bracket lists of stuff, right? Like `["apple", "banana"]`. To add something, you ...
🌐
Tech With Tech
techwithtech.com › home › json object vs. json array explained with python
JSON Object vs. JSON Array Explained With Python - Tech With Tech
November 6, 2022 - The JSON array here represents the value of the battery field in the JSON object: batteries = js_car ["battery"] >> print(batteries[0]) ... You can also pass a JSON array at the highest level of a JSON file or string.
🌐
HowToDoInJava
howtodoinjava.com › home › python json › python – append to json file
Python - Append to JSON File
December 9, 2022 - Learn to append JSON data into file in Python. To append, read the file to dict object, update the dict object and finally write the dict to the file.
🌐
Stack Overflow
stackoverflow.com › questions › 68571946 › python-how-to-append-a-json-object-to-a-json-array
Python: How to append a JSON object to a JSON array - Stack Overflow
import json with open("mydata.json", "r") as f: data = json.load(f) data["list"].append( {"a": "1"} ) with open("mydata.json", "w") as f: json.dump(data, f, indent=4) ... Sign up to request clarification or add additional context in comments.
🌐
JSON Schema
json-schema.org › understanding-json-schema › reference › array
JSON Schema - array
(This usage is often given a whole ... such as Python's tuple). List validation is useful for arrays of arbitrary length where each item matches the same schema. For this kind of array, set the items keyword to a single schema that will be used to validate all of the items in the array. In the following example, we define ...
Top answer
1 of 2
15

... the JSON array at the end of your answer is incorrect, but to generate an array, just give a list to json.dumps in Python. Something like json_data_list = []; ... ; json_data_list.append(json_data); ... print(json.dumps(json_data_list)); ...

2 of 2
2

Your JSON file is incorrect. Normally you must have a structure as:

{
    "key1": [
        {
            "id": "blabla",
            "name": "Toto"
        },
        {
            "id": "blibli",
            "name": "Tata"
        }
    ],
    "key2": {
        "id": "value"
    },
    "key3": "value"
}

So I think you have to change your JSON array for example as following:

{
    [
        {
            "id": 0,
            "organizer": "Some Name",
            "eventStart": "09:30 AM",
            "eventEnd": "10:00 AM",
            "subject": "rental procedure",
            "attendees": "Some Name<br />Person 2<br />Person 3"
        },
        {
            "id": 1,
            "organizer": "Some Name",
            "eventStart": "09:30 AM",
            "eventEnd": "10:00 AM",
            "subject": "rental procedure",
            "attendees": "Some Name<br />Person 2<br />Person 3"
        },
        {
            "id": 2,
            "organizer": "Some Name",
            "eventStart": "09:30 AM",
            "eventEnd": "10:00 AM",
            "subject": "rental procedure",
            "attendees": "Some Name<br />Person 2<br />Person 3"
        }
    ]
}

You can decide also to have not a list of dictionary as I proposed above but to use the ID value as key for each dictionary; in that case you have:

{
    "id0":{       
            "organizer": "Some Name",
            "eventStart": "09:30 AM",
            "eventEnd": "10:00 AM",
            "subject": "rental procedure",
            "attendees": "Some Name<br />Person 2<br />Person 3"
    },
    "id1":{       
            "organizer": "Some Name",
            "eventStart": "09:30 AM",
            "eventEnd": "10:00 AM",
            "subject": "rental procedure",
            "attendees": "Some Name<br />Person 2<br />Person 3"
    },
    "id2":{       
            "organizer": "Some Name",
            "eventStart": "09:30 AM",
            "eventEnd": "10:00 AM",
            "subject": "rental procedure",
            "attendees": "Some Name<br />Person 2<br />Person 3"
    }
}
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
Python has a built-in package called json, which can be used to work with JSON data. ... If you have a JSON string, you can parse it by using the json.loads() method.
🌐
Quora
quora.com › How-will-you-pass-values-to-the-JSON-array-using-Python
How will you pass values to the JSON array using Python? - Quora
Answer (1 of 4): Your question is so wrong on so many things. I won’t really tell you to read the manual. You don’t do this in one pass you see. JSON stands for JavaScript Object Notation, which means, it is Javascript, it is not Python, C or anything else.