【问题标题】:Python : Normalize Json response (array)Python:规范化 Json 响应(数组)
【发布时间】:2015-09-02 02:39:44
【问题描述】:

我是 JSON 和 Python 的新手,我正在尝试实现以下目标

下面需要解析JSON

{
    "id": "12345abc",
    "codes": [
       "BSVN1FKW3JKKNNMN",
        "HJYYUKJJL999OJR",
        "DFTTHJJJJ0099JUU",
        "FGUUKHKJHJGJJYGJ"
    ],
    "ctr": {
        "source": "xyz",
        "user_id": "1234"
    }
}

预期输出:在“代码”值上标准化

ID~CODES~USER_ID
12345abc~BSVN1FKW3JKKNNMN~1234
12345abc~HJYYUKJJL999OJR~1234
12345abc~DFTTHJJJJ0099JUU~1234
12345abc~FGUUKHKJHJGJJYGJ~1234

从下面开始,但需要帮助才能获得我想要的输出。

“代码”块可以有 n 个以逗号分隔的值。

下面的代码抛出错误“TypeError: string indices must be integers”

#!/usr/bin/python

import os
import json
import csv


f = open('rspns.csv','w')
writer = csv.writer(f,delimiter = '~')
headers = [‘ID’,’CODES’,’USER_ID’]
default = ''
writer.writerow(headers)

string = open('sample.json').read().decode('utf-8')
json_obj = json.loads(string)

#print json_obj['id']
#print json_obj['codes']
#print json_obj['codes'][0]
#print json_obj['codes'][1]
#print json_obj['codes’][2]
#print json_obj['codes’][3]
#print json_obj['ctr’][‘user_id']

for keyword in json_obj:
    row = []
    row.append(str(keyword['id']))
    row.append(str(keyword['codes']))
    row.append(str(keyword['ctr’][‘user_id']))
    writer.writerow(row)

【问题讨论】:

    标签: python arrays json


    【解决方案1】:

    如果您的 json_obj 看起来完全一样,那就是它是一本字典,那么问题是当您这样做时 -

    for keyword in json_obj:
    

    您正在迭代 json_obj 中的键,那么如果您尝试访问 ['id'] 以获取该键,它应该会错误提示 string indices must be integers。

    您应该在循环之前首先获取id 和user_id,然后循环遍历json_obj['codes'],然后将先前计算的id 和user_id 与codes 列表中的当前值一起添加到@ 987654332@csv 为一行。

    例子-

    import json
    import csv
    
    string = open('sample.json').read().decode('utf-8')
    json_obj = json.loads(string)
    
    with open('rspns.csv','w') as f:
        writer = csv.writer(f,delimiter = '~')
        headers = ['ID','CODES','USER_ID']
        writer.writerow(headers)
    
        id = json_obj['id']
        user_id = json_obj['ctr']['user_id']
    
        for code in json_obj['codes']:
            writer.writerow([id,code,user_id])
    

    【讨论】:

      【解决方案2】:

      您不想遍历json_obj,因为它是一个字典,并且遍历将获得键。 TypeError 是由于试图索引键('id'、'code' 和 'ctr')——它们是字符串——就好像它们是字典一样。

      相反,您希望json_obj['codes'] 中的每个代码都有单独的一行,并使用json_obj 字典进行查找:

      for code in json_obj['codes']:
          row = []
          row.append(json_obj['id'])
          row.append(code)
          row.append(json_obj['ctr’][‘user_id'])
          writer.writerow(row)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-23
        • 2019-05-07
        • 1970-01-01
        • 2019-03-24
        • 2020-08-03
        • 2016-06-10
        • 2015-06-22
        • 2022-08-11
        相关资源
        最近更新 更多