python - 在 Python 中解析 JSON 数组

标签 python arrays json parsing

我有一些 JSON 文件:

{
  "cis" : [ {
    "ucmdbId" : "835cfedfaabc32a1358b322ff3bae056",
    "type" : "running_software",
    "properties" : {
      "display_label" : "jboss (site1.ru)"
    }
  }, {
    "ucmdbId" : "7ef9f21c132c12b3d8d2af0964cc5970",
    "type" : "node",
    "properties" : {
      "display_label" : "site2.ru"
    }
  } ],
  "relations" : [ {
    "ucmdbId" : "80c42edbe32fbb4c25621756ec9e09d2",
    "type" : "compound_f",
    "properties" : null,
    "end1Id" : "23e30baf2320a3274d0aa1e7f56cdaef",
    "end2Id" : "15af0ba134327d32a0c5c72450e63fcd"
  }, {
    "ucmdbId" : "7fe9fb15d4462d1212aeee4aef2f32b4",
    "type" : "compound_f",
    "properties" : null,
    "end1Id" : "23e30baf2320a3274d0aa327f56cdaef",
    "end2Id" : "9232dd2621b814da632932e8cd33ffc8"
  } ]
}

我只需要 cis 数组。所以这就是我需要解析的内容:

[{
  "ucmdbId" : "835cfedfaabc32a1358b322ff3bae056",
  "type" : "running_software",
  "display_label" : "jboss (site1.ru)"
 }, {
  "ucmdbId" : "7ef9f21c132c12b3d8d2af0964cc5970",
  "type" : "node",
  "display_label" : "site2.ru"
}]

Python 脚本:

#!/usr/bin/python
import sys
import os
import tablib
import pandas as pd
import json
from pandas.io.json import json_normalize

f = open('/home/nik/test.json', 'rw')
jsonArray = f.read()
f.close
data = json.dumps(json.loads(jsonArray)['cis'])
jsonResult = pd.read_json(data)
array = json.loads(jsonArray)

print jsonArray
jsonResult.to_excel('/home/nik/output.xlsx', sheet_name='Sheet1')

但是我怎样才能得到关键参数呢?我尝试使用:

print data['type'].keys()
print data['type']

但它给我错误:

AttributeError: 'str' object has no attribute 'keys'

如何获得正确的 JSON 格式?

更新。解决方案:

谢谢,它有效。我将 JSON 导出到 xlsx 文件的完整代码:

#!/usr/bin/python
import subprocess
import sys
import os
import tablib
import pandas as pd
import json
import glob
import string

path = '/home/nik/json'
for jsonfile in glob.glob(os.path.join(path, '*.json')):
#jsonfile = '/home/nik/test.json'
    with open(jsonfile) as data_file:
        data = json.load(data_file)

    JSON = '[{ \n'
    for index, item in enumerate(data['cis']):
        ucmdbId = (item['ucmdbId'])
        type = (item['type'])
        display_label = (item['properties']['display_label'])
        Text1 = '  \"ucmdbId\" : \"%s\",' %(ucmdbId)
        Text2 = '  \"type\" : \"%s\",' %(type)
        Text3 = '  \"display_label\" : \"%s\",' %(display_label)
        if index==(len(data['cis'])-1):
            End = '}]'
        else:
            End = '}, {'
        JSON += Text3+'\n'+Text2+'\n'+Text1+'\n'+End+'\n'

    JSON = JSON.translate({ord(c): None for c in '\/'})
    jsonResult = pd.read_json(JSON)
    jsonResult = jsonResult.sort_values(by='type')
    jsonResult.to_excel(jsonfile+'.xlsx', sheet_name='Object monitoring', index=False)

最佳答案

import json
from pprint import pprint
jsonfile = 'C:\\temp\\temp.json' # path to your json file
with open(jsonfile) as data_file:    
    data = json.load(data_file)
pprint(data['cis'])

上面只会给你顺式数组。 下面是更细粒度的输出

for item in data['cis']:
    ucmdbId = (item['ucmdbId'])
    type = (item['type'])
    display_label = (item['properties']['display_label'])
    print(ucmdbId)
    print(type)
    print(display_label)

如果你想用键标签然后使用

for item in data['cis']:
    ucmdbId = (item['ucmdbId'])
    type = (item['type'])
    display_label = (item['properties']['display_label'])
    print('ucmdbId:{}'.format(ucmdbId))
    print('type:{}'.format(type))
    print('display_label:{}'.format(display_label))

关于python - 在 Python 中解析 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46447490/

相关文章:

python - 霍夫曼编码问题

c++ - "Empty"数组\vector 成员 C++

python - 保留 Pandas 中具有百分比重叠范围的行

javascript - 如何将 json 数组从 html 文件的脚本部分传递到 javascript 索引?

java - 如何从Java中的数组中提取最长的连续整数序列?

java 和 json jackson 属性 - 运行时的不同类型

C#更好地实现JSON文件

javascript - 将 html 元素映射到 json 对象

python - 无法使用 python 中的 aifc 模块读取 AIFF-C 文件

python - Python 代码中标识符错误中的无效字符