I have online JSON file where I have something like this:
{'skladiste': 1, 'sifra': '7138', 'nc': 0.8, 'vpc': 47.01, 'mpc': 55.0, 'stanje': 5.0, 'aktivan': 255, 'lokacija': '', 'atraktivanod': 0, 'atraktivando': 0}
{'skladiste': 2, 'sifra': '7138', 'nc': 0.8, 'vpc': 47.01, 'mpc': 55.0, 'stanje': 2.0, 'aktivan': 255, 'lokacija': '', 'atraktivanod': 0, 'atraktivando': 0}
Now I need to get that JSON data, sum ‘stanje’ for same key which is ‘sifra’ through whole JSON file. Is there any help?
I got JSON file data with this but I can not sum data
from urllib.request import urlopen
# import json
import json
# store the URL in url as
# parameter for urlopen
url = "https://www6.eline.ba/bl/RestWebShop.svc/json/CjenovniciZaWeb/ee6e994652884578830402a297ef3a93/tobyshop"
# store the response of URL
response = urlopen(url)
# storing the JSON response
# from url in data
data_json = json.loads(response.read())
# print the json response
print(data_json)
For example, there is ‘sifra’ 7138 repeated 2 times in this data with ‘stanje’ 5 and 2 and now I need to sum this two and export new data with only one ID 7138 and stanje with data of 7.
2
Answers
As I understand after reading your comments, your goal is to have the same json as output, just grouping those elements that have the same ‘sifra’.
These are the steps needed:
First step is to get the list of items from the json, that is inside the key ‘cjenovnici’:
Then you sort the list using ‘sifra’:
And once the list is sorted you can use
groupby
to create a new list:Now you can replace the original list with the grouped list in data_json:
And as final step you can save the data as a new json file:
You can iterate the json the sum them.
Code:
Output: