3

I've got a valid JSON object, with a number of bike accidents listed:

{
   "city":"San Francisco",
   "accidents":[
      {
         "lat":37.7726483,
         "severity":"u'INJURY",
         "street1":"11th St",
         "street2":"Kissling St",
         "image_id":0,
         "year":"2012",
         "date":"u'20120409",
         "lng":-122.4150145
      },

   ],
   "source":"http://sf-police.org/"
}

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. I've loaded my json like so:

with open('sanfrancisco_crashes_cp.json', 'rw') as json_data:
   json_data = json.load(json_data)
   accidents = json_data['accidents']

When I try to write to the file like so:

for accident in accidents:
   turn = randTurn()
   accidents.write(accident['Turn'] = 'right')

I get the following error: SyntaxError: keyword can't be an expression

I've tried a number of different ways. How can you add data to a JSON object using Python?

1
  • As a side note, "JSON object" is a really confusing term. You've got the Python dictionary that the JSON decodes to/encodes from, and you've got the string of text that it's encoded as, and it's always ambiguous which one you're talking about when you say "JSON object". It's better to be absolutely clear about which one you mean. Commented Nov 3, 2014 at 20:34

2 Answers 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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.