在python中解析json数据 [英] Parse json data in python
问题描述
我无法解析生成的json数据以仅返回所需的部分(例如,名称,过道,状态)。如何修改输出以仅打印这些项目?
I am having trouble parsing the resulting json data to return only wanted section (e.g., 'name, 'aisle', 'status'). How can I modify the output to only print those items?
代码:
for coro in tqdm(asyncio.as_completed(tasks, loop=loop)):
try:
response = await coro
if response is None:
continue
data, store = response
result = json.loads(data['searchResults'])['results'][0]
summary = {
'name': result['name'],
'aisle': result['price']['aisle'][0],
'status': result['inventory']['status'],
}
results[store] = summary
except (IndexError, KeyError):
continue
with open('Testing.txt', 'w') as outfile:
json.dump(results, outfile, indent = 2)
outfile.write('\n')
我打印时会得到以下格式:
When I print I get the following format:
{
"1": {
"name": "camera",
"aisle": "M.3",
"status": "In Stock"
},
"2": {
"name": "camera",
"aisle": "M.53",
"status": "Out of Stock"
},
"3":{
"name": "camera",
"aisle": "M.32",
"status": "In Stock"
}
}
I希望在单个行上每个循环的输出,例如:
I would like the output for each loop on a single line, such as:
'35': { 'name': 'Camera', 'aisle': 'M.35', 'status': 'Out of stock' },
'36': { 'name': 'Camera', 'aisle': 'J.35', 'status': 'In stock' }
推荐答案
仅供参考-输出文件中的样本数据看起来错误,因为值字符串不是有效的json。应该是这样的:
FYI—the sample data from the output file looks wrong because the value string is not valid json. It should be like this:
"{\"results\":[{\"name\":\"Camera\",\"department\":{\"name\":\"Electronics\",\"storeDeptId\":-1},\"location\":{\"aisle\":[\"M.35\"],\"detailed\":[{\"zone\":\"M\",\"aisle\":\"36\",\"section\":\"2\"}]},\"price\":{\"priceInCents\":49900,\"isRealTime\":true,\"currencyUnit\":\"USD\"},\"inventory\":{\"quantity\":3,\"status\":\"Out of stock\",\"isRealTime\":true}}]}"
请注意,我的JSON版本中的]
不在您的JSON版本中。获得有效的JSON后,您可以使用json.loads将该JSON字符串转换为可以从其中提取数据的值:
Note the ]
that is in my version of your JSON but not in yours. Once you get to valid JSON, you can use json.loads to transform that JSON string into a value that you can pull data out of:
data = json.loads(data['searchResults'])
print json.dumps(data, indent=2)
应该会给您带来帮助:
{
"results": [
{
"department": {
"name": "Electronics",
"storeDeptId": -1
},
"inventory": {
"status": "Out of stock",
"isRealTime": true,
"quantity": 3
},
"price": {
"priceInCents": 49900,
"isRealTime": true,
"currencyUnit": "USD"
},
"name": "Camera",
"location": {
"detailed": [
{
"aisle": "36",
"section": "2",
"zone": "M"
}
],
"aisle": [
"M.35"
]
}
}
]
}
现在,类似这样的操作将使您接近所需的修剪输出:
Now, something like this will get you close to the trimmed output you want:
for coro in asyncio.as_completed(tasks, loop=loop):
try:
data, store = await coro
result = json.loads(data['searchResults'])['results'][0] #Storing retrieved json data
summary = {
'name': result['name'],
'aisle': result['location']['aisle'][0],
'status': result['inventory']['status'],
}
results[store] = summary
except (IndexError):
continue
此后,输出文件中的输出将类似于:
After this, the output in your output file will look something like:
'35': { 'name': 'Camera', 'aisle': 'M.35', 'status': 'Out of stock' },
这篇关于在python中解析json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!