将API响应转换为json

时间:2019-07-04 15:23:27

标签: python json

我使用Flickr API photo.search得到以下响应

jsonFlickrApi({"photos":{"page":1,"pages":3786,"perpage":100,"total":"378562","photo":[{"id":"48197008707","owner":"22430972@N05","secret":"36b279092c","server":"65535","farm":66,"title":"Callum and our Cat friend, 5th June 2019.","ispublic":1,"isfriend":0,"isfamily":0},{"id":"48196846446","owner":"156701458@N02","secret":"d650bc4c35","server":"65535","farm":66,"title":"\u2606 Post Nr. 294 SENSE \u2013 Celestinas Kids, Parke Ave. & Posh and Tm:.Creation \u2606","ispublic":1,"isfriend":0,"isfamily":0}...{"id":"48196265577","owner":"61762095@N08","secret":"db8d31c2b2","server":"65535","farm":66,"title":"190702_028.jpg","ispublic":1,"isfriend":0,"isfamily":0}]},"stat":"ok"})

我在中间添加了...,因为响应太长以至于无法共享所有内容,如何将其隐藏到JSON对象(包含“照片”中的字典列表的字典。如果我使用json.dumps直接将它弄乱,即被当作一个字符串

3 个答案:

答案 0 :(得分:0)

如果您确定文本将以“ jsonFlickrApi(”开头,则可以将其解析。您可以将变量start更改为其他一些起始字符串。

如果您需要更高级的匹配工具,则正则表达式是正确的工具

str = r"""jsonFlickrApi({"photos":{"page":1,"pages":3786,"perpage":100,"total":"378562","photo":[{"id":"48197008707","owner":"22430972@N05","secret":"36b279092c","server":"65535","farm":66,"title":"Callum and our Cat friend, 5th June 2019.","ispublic":1,"isfriend":0,"isfamily":0},{"id":"48196846446","owner":"156701458@N02","secret":"d650bc4c35","server":"65535","farm":66,"title":"\u2606 Post Nr. 294 SENSE \u2013 Celestinas Kids, Parke Ave. & Posh and Tm:.Creation \u2606","ispublic":1,"isfriend":0,"isfamily":0}...{"id":"48196265577","owner":"61762095@N08","secret":"db8d31c2b2","server":"65535","farm":66,"title":"190702_028.jpg","ispublic":1,"isfriend":0,"isfamily":0}]},"stat":"ok"})"""

start = len("jsonFlickrApi("); 

json.loads(str[start: -1]);

更新以重新

由于它是来自其他API的响应,因此我认为json对象有效。模式也很简单

str = r"""jsonFlickrApi({"photos":{"page":1,"pages":3786,"perpage":100,"total":"378562","photo":[{"id":"48197008707","owner":"22430972@N05","secret":"36b279092c","server":"65535","farm":66,"title":"Callum and our Cat friend, 5th June 2019.","ispublic":1,"isfriend":0,"isfamily":0},{"id":"48196846446","owner":"156701458@N02","secret":"d650bc4c35","server":"65535","farm":66,"title":"\u2606 Post Nr. 294 SENSE \u2013 Celestinas Kids, Parke Ave. & Posh and Tm:.Creation \u2606","ispublic":1,"isfriend":0,"isfamily":0}...{"id":"48196265577","owner":"61762095@N08","secret":"db8d31c2b2","server":"65535","farm":66,"title":"190702_028.jpg","ispublic":1,"isfriend":0,"isfamily":0}]},"stat":"ok"})"""


jsonStr = re.findall("{.*}",str)[0]
json.loads(jsonStr)

答案 1 :(得分:0)

您可以使用正则表达式提取JSON格式的数据,然后使用json.loads

import re
import json

text = 'jsonFlickrApi({"photos":[{"id":"A", "title":"Hello"}, {"id":"B", "title":"World"}]})'

result = re.fullmatch('[ ]*jsonFlickrApi[ ]*\((.+?)\)[ ]*', text)
print(json.loads(result.group(1)))

输出:

{'photos': [{'id': 'A', 'title': 'Hello'}, {'id': 'B', 'title': 'World'}]}

答案 2 :(得分:0)

您必须将正文作为字符串获取 使用 json.parse(response) 它应该可以解决问题