我从api url获得了两个字符串
pagehandle = urllib2.urlopen(ariel_url+"?%s" % params1)
data1 = pagehandle.read();
pagehandle = urllib2.urlopen(ariel_url+"?%s" % params2)
data2 = pagehandle.read();
data1和data2包含以下string
{"priority":"HIGH", "titles":["Brand", "Likes"], "values":[["addidas", 130],["nike", 180]]}
{"priority":"HIGH", "titles":["Brand", "Likes"], "values":[["iphone", 49],["ipod", 590]]}
我想将这两个字符串转换为json并组合(或组合字符串然后转换),以便输出json可能喜欢
{"priority":"HIGH", "titles":["Brand", "Likes"], "values":[["addidas", 130],["nike", 180],["iphone", 49],["ipod", 590]]]}
我该怎么做?我更喜欢使用simplejson库
答案 0 :(得分:3)
这些不是字符串,而是字典。您可以将这些字典组合在一起:
def combine(dict1, dict2):
if dict1['priority'] == dict2['priority'] and dict1['titles'] == dict2['titles']:
return {
'priority': dict1['priority'],
'titles': dict1['titles'],
'values': dict1['values'] + dict2['values']
}
之后你只需运行:
import json
json.dumps(combine(dict1, dict2))
你会得到这两个组合词典的json。
修改强>
所以我理解你真正得到的是:
s1 = '{"priority":"HIGH", "titles":["Brand", "Likes"], values:[["addidas", 130],["nike", 180]]}'
s2 = '{"priority":"HIGH", "titles":["Brand", "Likes"], values:[["iphone", 49],["ipod", 590]]}'
在这种情况下,您可以运行:
dict1 = json.loads(s1)
dict2 = json.loads(s2)
result = combine(dict1, dict2)
答案 1 :(得分:3)
你走了:
import json
a = json.loads('{"priority":"HIGH", "titles":["Brand", "Likes"], "values":[["addidas", 130],["nike", 180]]}')
b = json.loads('{"priority":"HIGH", "titles":["Brand", "Likes"], "values":[["iphone", 49],["ipod", 590]]}')
for value in a['values']:
b['values'].append(value)
# edited
json.dumps(b)