Json解析(for循环)不起作用

时间:2018-03-21 14:30:35

标签: python json

我正在尝试解析json文件(data.json)&当我得到一个没有任何data_block键的空响应(data_empty.json)时,也试图处理异常。

check_key& for循环似乎没有做任何事情,但打印命令有效。

- data.json

{
  "response": {
    "numFound": 1,
    "data_block": [
      {
        "Number": "11097",
        "ID": -61000,
        "Version": "18",
        "Sequence": [
          "1",
          "2",
          "3"
        ],
        "Status": [
          "Booked",
          "Canceled",
          "Canceled"
        ],
        "Name": "abc",
        "EmailAddress": "abc@test.com"
      },
      {
        "Number": "00001",
        "ID": -1000,
        "Version": "1",
        "Sequence": [
          "1"
        ],
        "Status": [
          "Booked"
        ],
        "Name": "xyz",
        "EmailAddress": "xyz@test.com"
      }

    ]
  }
}

- data_empty.json

{
  "response": {
    "numFound": 0,
    "data_block": []
  }
}

我有以下代码来解析json(data.json),只有打印工作,但我无法使for循环工作。

import json
from pprint import pprint
import csv

data = json.load(open('data.json'))
#data = json.load(open('data_empty.json'))
#pprint(data)

output_file_name = 'api_rspns.csv'


#create out file
f = open(output_file_name,'w')
writer = csv.writer(f,delimiter = '~')
headers = ['ORDER_NBR','ORDER_STATUS','EMAIL']
writer.writerow(headers)


print(data['response']['data_block'][0]['Number'])
print(data['response']['data_block'][0]['Status'])
print(data['response']['data_block'][0]['EmailAddress'])

print(data['response']['data_block'][1]['Number'])
print(data['response']['data_block'][1]['Status'])
print(data['response']['data_block'][1]['EmailAddress'])


#check for KeyError ,only parse if ['data_block'] present
try:
    check_key = data['response']['data_block'][0]
except KeyError:
    #continue

    for trip in check_key:
        row = []
        row.append(trip['Number'])
        #row.append(trip["Status"])
        writer.writerow(row)
f.close()

1 个答案:

答案 0 :(得分:0)

下面的代码现在可以使用(也有空的回复),谢谢你的帮助

#check for KeyError ,only parse if ['data_block'] present
#try:
#    check_key = data['response']['data_block'][0]
#except KeyError:
    #continue

for trip in data['response']['data_block']:
    row = []
    row.append(trip['Number'])
    row.append(trip["Status"])
    writer.writerow(row)
f.close()