我是 JSON 新手。我正在做一个车辆牌照检测的项目。 我有一个以下形式的数据集:
{"content": "http://com.dataturks.a96-i23.open.s3.amazonaws.com/2c9fafb0646e9cf9016473f1a561002a/77d1f81a-bee6-487c-aff2-0efa31a9925c____bd7f7862-d727-11e7-ad30-e18a56154311.jpg.jpeg","annotation":[{"label":["number_plate"],"notes":"","points":[{"x":0.7220843672456576,"y":0.5879828326180258},{"x":0.8684863523573201,"y":0.6888412017167382}],"imageWidth":806,"imageHeight":466}],"extras":null},
{"content": "http://com.dataturks.a96-i23.open.s3.amazonaws.com/2c9fafb0646e9cf9016473f1a561002a/4eb236a3-6547-4103-b46f-3756d21128a9___06-Sanjay-Dutt.jpg.jpeg","annotation":[{"label":["number_plate"],"notes":"","points":[{"x":0.16194331983805668,"y":0.8507795100222717},{"x":0.582995951417004,"y":1}],"imageWidth":494,"imageHeight":449}],"extras":null},
总共有240个数据块。 我想用上面的数据集做两件事。 首先,我需要下载每个块中的所有图像,其次,需要将“点”列的值获取到文本文件。
我在获取列的值时遇到问题。
import json
jsonFile = open('Indian_Number_plates.json', 'r')
x = json.load(jsonFile)
for criteria in x['annotation']:
for key, value in criteria.iteritems():
print(key, 'is:', value)
print('')
我编写了上面的代码来获取“注释”下的所有值。 但是,出现以下错误
Traceback (most recent call last):
File "prac.py", line 13, in <module>
x = json.load(jsonFile)
File "C:\python364\Lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\python364\Lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\python364\Lib\json\decoder.py", line 342, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 394 (char 393)
请帮助我获取“点”列的值,并从“内容”部分的链接下载图像。
我在搜索时找到了这个答案。本质上,您可以读取一个对象,当 JSON 看到意外对象时捕获异常,然后查找/重新解析并构建对象列表。
在 Java 中,我只是告诉你使用 Jackson 和他们的 SAX 风格的流接口,因为我已经这样做来读取这样格式化的对象列表 - 如果 python 中的 JSON 有一个流 api,我会使用它而不是异常处理程序解决方法
出现错误是因为您的文件包含两条或更多记录:
{"content": "http://com.dataturks.a96- } ..... {"content": .....
要解决此问题,您应该重新格式化 json,以便所有记录都包含在一个数组中:
{ "data" : [ {"content": "http://com.dataturks.a96- .... },{"content":... }]}
要下载图像,请提取图像名称和网址并使用请求:
import requests
with open(image_name, 'wb') as handle:
response = requests.get(pic_url, stream=True)
if not response.ok:
print response
for block in response.iter_content(1024):
if not block:
break
handle.write(block)
使用这段代码读取带有lines=True标志的JSON文件,然后删除多余的:
df = pd.read_json(local_path,lines=True)
pd.set_option('display.max_colwidth', -1)
# delete the extras column
del df['extras']
# check the data dataframe
df.head()