修改JSON脚本继续根据ID
问题描述:
我有一个包含JSON文件的重复值之一:修改JSON脚本继续根据ID
[{"id": "0",
"Name": "John",
"Blah": "m",
...
...}
{
"id": "2",
"Name": "John",
"Blah", "m",
...
...},
{
"id": "1",
"Name": "Ron",
"Blah", "r",
...
...},
{
"id": "0",
"Name": "Jake",
"Blah", "s",
...
...}]
,你可以一切是id的旁边一样。我想要做的事情我想保留id = 2的那个,并删除id = 0的那个。
因此,修改后的文件应该是这样的:
[{
"id": "2",
"Name": "John",
"Blah", "m",
...
...},
{
"id": "1",
"Name": "Ron",
"Blah", "r",
...
...},
{
"id": "0",
"Name": "Jake",
"Blah", "s",
...
...}]
这是我到目前为止有:
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()
上述X-包含列表。我无法弄清楚如何迭代元组元素。
但它给我的错误:
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
我试图寻找对计算器的例子。此外,试图将x更改为int或字符串。不起作用,任何帮助将不胜感激。
答
感谢的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
因此,它是纯粹* *要使用的'Name'关键是?或者还有'Blah'键? –
错误告诉你'jsons'是*列表的列表*,而不是字典列表。 –
也许你需要仔细看看'jsons'包含的内容。错误告诉你'x'是一个列表,而不是一个字典。 –