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
.
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
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. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }.
Functions Used:
- json.loads[]: json.loads[] function is present in python built-in ‘json’ module. This function is used to parse the JSON
string.
Syntax: json.loads[json_string]
Parameter: It takes JSON string as the parameter.
Return type: It returns the python dictionary object.
- json.dumps[]: json.dumps[] function is present in python built-in ‘json’ module. This function is used to convert Python object into JSON string.
Syntax: json.dumps[object]
Parameter: It takes Python Object as the parameter.
Return type: It returns the JSON string.
- update[]: This method updates the dictionary with elements from another dictionary object or from an iterable key/value pair.
Syntax: dict.update[[other]]
Parameters: Takes another dictionary or an iterable key/value pair.
Return type: Returns None.
Example 1: Updating a JSON string.
Python3
import
json
x
=
'{
"organization"
:
"GeeksForGeeks"
,
"city"
:
"Noida"
,
"country"
:
"India"
}'
y
=
{
"pin"
:
110096
}
z
=
json.loads[x]
z.update[y]
print
[json.dumps[z]]
Output:
{“pin”: 110096, “organization”: “GeeksForGeeks”, “country”: “India”, “city”: “Noida”}
Example 2: Updating a JSON file. Suppose the JSON file looks like this.
We want to add another JSON data after emp_details. Below is the implementation.
Python3
import
json
def
write_json[new_data, filename
=
'data.json'
]:
with
open
[filename,
'r+'
] as
file
:
file_data
=
json.load[
file
]
file_data[
"emp_details"
].append[new_data]
file
.seek[
0
]
json.dump[file_data,
file
, indent
=
4
]
y
=
{
"emp_name"
:
"Nikhil"
,
"email"
:
""
,
"job_profile"
:
"Full Time"
}
write_json[y]
Output: