是否有一种有效的方法可以删除重复内容' person_id'这个数据与python的字段?在这种情况下,只需保留第一次出现。
{
{obj_id: 123,
location: {
x: 123,
y: 323,
},
{obj_id: 13,
location: {
x: 23,
y: 333,
},
{obj_id: 123,
location: {
x: 122,
y: 133,
},
}
应该成为:
{
{obj_id: 123,
location: {
x: 123,
y: 323,
},
{obj_id: 13,
location: {
x: 23,
y: 333,
},
}
答案 0 :(得分:7)
假设您的JSON是有效的语法,并且您确实需要Python
的帮助,您需要做这样的事情
import json
ds = json.loads(json_data_string) #this contains the json
unique_stuff = { each['obj_id'] : each for each in ds }.values()
如果你想永远保留第一次出现,你需要做这样的事情
all_ids = [ each['obj_id'] for each in ds ] # get 'ds' from above snippet
unique_stuff = [ ds[ all_ids.index(id) ] for id in set(ids) ]
答案 1 :(得分:4)
这是一个实现,它保留输入json对象的顺序,并保持第一次出现具有相同id的对象:
import json
import sys
from collections import OrderedDict
L = json.load(sys.stdin, object_pairs_hook=OrderedDict)
seen = OrderedDict()
for d in L:
oid = d["obj_id"]
if oid not in seen:
seen[oid] = d
json.dump(seen.values(), sys.stdout, indent=2)
[
{
"obj_id": 123,
"location": {
"x": 123,
"y": 323
}
},
{
"obj_id": 13,
"location": {
"x": 23,
"y": 333
}
},
{
"obj_id": 123,
"location": {
"x": 122,
"y": 133
}
}
]
[
{
"obj_id": 123,
"location": {
"x": 123,
"y": 323
}
},
{
"obj_id": 13,
"location": {
"x": 23,
"y": 333
}
}
]
答案 2 :(得分:-1)
(如果你有有效的json)
from simplejson import loads, dumps
dumps(loads(my_json))
答案 3 :(得分:-2)
这不是有效的JSON。在有效的JSON(数组)上,您可以使用jQuery $ .each并查看Obj_id以查找和删除重复项。
这样的事情:
$.each(myArrayOfObjects, function(i, v)
{
// check for duplicate and add non-repeatings to a new array
});