用Python解析JSON数组
我有一些JSON文件:用Python解析JSON数组,python,arrays,json,parsing,Python,Arrays,Json,Parsing,我有一些JSON文件: { "cis" : [ { "ucmdbId" : "835cfedfaabc32a1358b322ff3bae056", "type" : "running_software", "properties" : { "display_label" : "jboss (site1.ru)" } }, { "ucmdbId" : "7ef9f21c132c12b3d8d2af0964cc5970", "typ
{
"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文件的完整代码:
以上内容将为您提供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))
data['type']
返回类似于“运行软件”
。这是一个字符串,不是字典。数据['type']
将是一个str
对象,即“运行软件”
或“节点”
。此对象没有.key()
方法。你以为会发生什么?
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))