浏览python中的dict列表

问题描述 投票:-1回答:1

我需要浏览一个python字典列表,我的列表如下

{
  "type" : "record",
  "name" : "warranty",
  "doc" : "Schema generated by Kite",
  "fields" : [ {
    "name" : "id",
    "type" : "long",
    "doc" : "Type inferred from '1'"
  }, {
    "name" : "train_id",
    "type" : "long",
    "doc" : "Type inferred from '21691'"
  }, {
    "name" : "siemens_nr",
    "type" : "string",
    "doc" : "Type inferred from 'Loco-001'"
  }, {
    "name" : "uic_nr",
    "type" : "long",
    "doc" : "Type inferred from '193901'"
  }, {
    "name" : "Configuration",
    "type" : "string",
    "doc" : "Type inferred from 'ZP28'"
  }, {
    "name" : "Warranty_Status",
    "type" : "string",
    "doc" : "Type inferred from 'Out_of_Warranty'"
  }]

我怎样才能获得字段实体的名称和类型谢谢(ps:它是一个JSON文件)

我写了这段代码:

   with open('/data/my-data/archive/in/test_warranty_data.csv.txt.avro.txt', 'r') as f:   
    i=0
    data = json.load(f)
    for ele in data["fields"]:
      print ele.[i].["name"]
      print ele.[i].["type"]
      i++

可能你可以建议我更高效的东西:)谢谢

python json list dictionary
1个回答
0
投票

我假设您有以下名为data.json的json文件:

{
  "fields" : [ {
    "name" : "id",
    "type" : "long",
    "doc" : "Type inferred from '1'"
  }, {
    "name" : "train_id",
    "type" : "long",
    "doc" : "Type inferred from '21691'"
  }, {
    "name" : "siemens_nr",
    "type" : "string",
    "doc" : "Type inferred from 'Loco-001'"
  }, {
    "name" : "uic_nr",
    "type" : "long",
    "doc" : "Type inferred from '193901'"
  }]
}

以下代码可以帮助提取名称和类型:

import json

f = open("data.json", "r")
data = json.load(f)
fields = data["fields"]
for field in fields:
    print(field['name'])
    print(field['type'])
    print("==================")

输出是:

id
long
==================
train_id
long
==================
siemens_nr
string
==================
uic_nr
long
==================
© www.soinside.com 2019 - 2024. All rights reserved.