0

I have a JSON that look like:

[{
    "lat": 43.96063343238712,
    "panoid": "sffcNG69c2kdZwEuYp1htw",
    "lon": 3.098330084924494
}, {
    "lat": 43.96052745649745,
    "panoid": "2rJPv_r0gC5FBPLZK5vHDA",
    "lon": 3.098487422195691
} and so on... ]

I want for each element (means pair of brackets), to add a key calc that is equal to

(value of "lat") - 50

How could I do to update my JSON like that? I guess I should convert the JSON into a dictionary. But how to proceed after?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Julien
  • 45
  • 1
  • 3
  • 15
  • 1
    You'll need to parse the JSON into a list of dictionary at some point, so where exactly are you stuck? – OneCricketeer Aug 22 '18 at 13:22
  • I don't really see how to add the new row and then populate it. – Julien Aug 22 '18 at 13:26
  • Possible duplicate of [Add new keys to a dictionary?](https://stackoverflow.com/questions/1024847/add-new-keys-to-a-dictionary) –  Aug 22 '18 at 13:28
  • 1
    JSON doesn't have "rows", it has keys and values. You add a pairing in python just as you would a regular dictionary. JSON is parsed into a dictionary, and dictionaries can be written out as JSON files, but that's an implementation detail. – OneCricketeer Aug 22 '18 at 13:35
  • Ok thanks for your answers – Julien Aug 22 '18 at 13:38
  • @cricket_007 JSON isn't just dictionaries, it can have arrays too. –  Aug 22 '18 at 13:43
  • @Term True, lists and primitives are there. For the purpose of the problem, though, a dictionary would be used – OneCricketeer Aug 22 '18 at 13:45

1 Answers1

2

Use the json module to load the string into a list. Iterate over the dictionaries in the list and set an attribute - calc - to be the lat value minus 50.

Finally, if required, dump the list back to a string with an optional indent arg for pretty-printing.

import json
s = '''[{
    "lat": 43.96063343238712,
    "panoid": "sffcNG69c2kdZwEuYp1htw",
    "lon": 3.098330084924494
}, {
    "lat": 43.96052745649745,
    "panoid": "2rJPv_r0gC5FBPLZK5vHDA",
    "lon": 3.098487422195691
}]'''
l = json.loads(s)
for d in l:
    d['calc'] = d['lat'] - 50
print(json.dumps(l, indent=4))

giving:

[
    {
        "lat": 43.96063343238712,
        "panoid": "sffcNG69c2kdZwEuYp1htw",
        "lon": 3.098330084924494,
        "calc": -6.0393665676128805
    },
    {
        "lat": 43.96052745649745,
        "panoid": "2rJPv_r0gC5FBPLZK5vHDA",
        "lon": 3.098487422195691,
        "calc": -6.039472543502548
    }
]
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54