I have a json file containing:
[{"id": "0",
"Name": "John",
"Blah": "m",
...
...}
{
"id": "2",
"Name": "John",
"Blah", "m",
...
...},
{
"id": "1",
"Name": "Ron",
"Blah", "r",
...
...},
{
"id": "0",
"Name": "Jake",
"Blah", "s",
...
...}]
As you can everything else is same beside the id's. What I want to do I would like to keep the one with id=2 and delete the one with id=0.
So, after modification file should look like:
[{
"id": "2",
"Name": "John",
"Blah", "m",
...
...},
{
"id": "1",
"Name": "Ron",
"Blah", "r",
...
...},
{
"id": "0",
"Name": "Jake",
"Blah", "s",
...
...}]
This is what I have so far:
with open(filename+'.json') as f:
# load json objects to dictionaries
jsons = map(json.loads, f)
uniques = {x['Name']: x for x in jsons}
# write to new json file
with open(filename+"Output"+'.json' ,'w') as nf:
json.dump(uniques.values(), nf)
print uniques.values()
Above x contains the list. I am not able to figure out how I can iterate over the tuple elements.
But it gives me the error:
Traceback (most recent call last):
File "readJsonFile.py", line 18, in <module>
uniques = {x['PlayerName']: x for x in jsons}
File "readJsonFile.py", line 18, in <dictcomp>
uniques = {x['PlayerName']: x for x in jsons}
TypeError: list indices must be integers, not str
I tried looking for an example on stackoverflow. Also, tried to change the x to an int or string. Doesn't work, any help will be appreciated.
答案 0 :(得分:0)
感谢Martijn Pieters
解决方案是:
#Opening File
with open(filename+'.json') as f:
d = json.load(f)
#Printing Unique data
uniques = {str(x['Name']): x for x in d}
print "unique vals:",uniques