如何使用python从列表Json中获取数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30510352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get data from a list Json with python?
提问by Colours123
I am new to python and have tried to get data from a python json document , what I try to do is pass the information to python and json from python print a pdf with a table style. My code in json is
我是 python 的新手,并试图从 python json 文档中获取数据,我尝试做的是将信息传递给 python 和 json 从 python 打印具有表格样式的 pdf。我在 json 中的代码是
[
{
"files": 0,
"data": [
{"name": "RFC", "value": "XXXXXXX", "attId": 01},
{"name": "NOMBRE", "value": "JOSE", "attId": 02},
{"name": "APELLIDO PATERNO", "value": "MONTIEL", "attId": 03},
{"name": "APELLIDO MATERNO", "value": "MENDOZA", "attId": 04},
{"name": "FECHA NACIMIENTO", "value": "1989-02-04", "attId": 05}
],
"dirId": 1,
"docId": 4,
"structure": {
"name": "personales",
"folioId": 22
}
},
{
"files": 0,
"data": [
{"name": "CALLE", "value": "AMOR", "attId": 06},
{"name": "No. EXTERIOR", "value": "4", "attId": 07},
{"name": "No. INTERIOR", "value": "2", "attId": 08},
{"name": "C.P.", "value": "55060", "attId": 09},
{"name": "ENTIDAD", "value": "ESTADO DE MEXICO", "attId": 10},
{"name": "MUNICIPIO", "value": "ECATEPEC", "attId": 11},
{"name": "COLONIA", "value": "INDUSTRIAL", "attId": 12}
],
"dirId": 1,
"docId": 4,
"structure": {
"name": "direccion",
"folioId": 22
}
}
]
and in python i tip the next code
在 python 中,我提示下一个代码
import json
f= open(prueba.json)
prueba = json.load(f)
prueba
print correctly content of json,but my idea is get only for example:
正确打印json的内容,但我的想法只是例如:
Nombre,Jose
and then use the parameters to build the table in pdf
然后使用参数在pdf中构建表格
I have tried the following
我已经尝试了以下
import json
json_data = []
with open('prueba.json') as json_file:
json_data = json.load(json_file)
for key, value in json_data.iteritems():
print key;
for item in value:
print item
for key, value in json_data.iteritems():
print key;
for item in value:
print item
But i have the next error:
但我有下一个错误:
AttributeError : 'list' object has no attribute 'iteritems'
I 'm trying to do something for them but I must get each data of json
我正在尝试为他们做点什么,但我必须获取 json 的每个数据
采纳答案by konart
json_data = [] # your list with json objects (dicts)
for item in json_data:
for data_item in item['data']:
print data_item['name'], data_item['value']
回答by Marco Rossi
Something like
就像是
for key, value in json_data.iteritems():
print key
if isinstance(value, (list, tuple)):
for item in value:
print item
if isinstance(value, (dict)):
for value_key,value_value in value.iteritems():
print value_key,str(value_value)
Can be improved to manage more types and can be made recursive.
可以改进以管理更多类型,并且可以递归。