如何从json文件中获取嵌套键值

时间:2018-07-02 20:32:01

标签: python json python-3.x

我具有以下结构:

{
  "$schema": "http:",
  "title": "al",
  "description": "An enitity ",
  "id": "a.json#",
  "type": "object",
  "required": [
    "symbol",
    "symbolText",
    "gene",
    "taxonId",
    "primaryId"
  ],
  "additionalProperties": false,
  "properties": {
    "primaryId": {
      "$ref": "..",
      "description": "The"
    },
    "symbol": {
      "type": "string",
      "description": "The symbol of the entity."
    },
    "symbolText": {
      "type": "string",
      "description": "the "
    },
    "taxonId": {
      "$ref": "../g",
      "description": "The "
    },
    "synonyms": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "uniqueItems": true
    },
    "secondaryIds": {
      "type": "array",
      "items": {
        "$ref": "."
      },
      "uniqueItems": true
    },
    "gene": {
      "$ref": "../globalId.json#/properties/globalId",
      "description": "The "
    },
    "crossReferences": {
      "description": "Collection",
      "type": "array",
      "items": {
        "$ref": "../crossReference.json#"
      },
      "uniqueItems": true
    }
  }
}

保存在名为“ my_keywordfile”的文件中。 我想要类似的东西:

$schema.http,
type.object,
...,
**properties.primaryId.$ref,
properties.primaryId.description**

这是我拥有的代码:

json_load = json.load(my_keywordfile)    
for key, value in json_load.items():
    # print((key,value))
    if type(value) == type({}) or type(value) == type([]):
        for x in value:
            for i in range(0, len(value) > i):
                 print(key+'.'+value)

但是它给了我这个错误:

TypeError: must be str, not list

有人知道如何解决它吗?直到这行都可以正常工作:

for key, value in json_load.items():
        print((key,value))

此部分在第一层打印出键及其值。 但是其余的代码似乎有问题!

3 个答案:

答案 0 :(得分:0)

您需要此行才能打印x而不是value,并且可以删除for i in range(0, len(value) > i):

for x in value:
    print(key+'.'+x)

答案 1 :(得分:0)

def get_dotted_form(val, old=""):
    lines = []
    if isinstance(val, dict):
        for k in val.keys():
            lines += get_dotted_form(val[k], old + "." + str(k))
    elif isinstance(val, list):
        for i,k in enumerate(val):
            lines += get_dotted_form(k, old + "." + str(i))
    else:   
        lines += ["{}.{}".format(old,str(val))]

    return [line.lstrip('.') for line in lines]

dotted_list = get_dotted_form(json_data)
dotted_string = ',\n'.join(s)
print (dotted_string)

输出

$schema.http:,
title.al,
description.An enitity ,
id.a.json#,
type.object,
required.0.symbol,
required.1.symbolText,
required.2.gene,
required.3.taxonId,
required.4.primaryId,
additionalProperties.False,
properties.primaryId.$ref...,
properties.primaryId.description.The,
properties.symbol.type.string,
properties.symbol.description.The symbol of the entity.,
properties.symbolText.type.string,
properties.symbolText.description.the ,
properties.taxonId.$ref.../g,
properties.taxonId.description.The ,
properties.synonyms.type.array,
properties.synonyms.items.type.string,
properties.synonyms.uniqueItems.True,
properties.secondaryIds.type.array,
properties.secondaryIds.items.$ref..,
properties.secondaryIds.uniqueItems.True,
properties.gene.$ref.../globalId.json#/properties/globalId,
properties.gene.description.The ,
properties.crossReferences.description.Collection,
properties.crossReferences.type.array,
properties.crossReferences.items.$ref.../crossReference.json#,
properties.crossReferences.uniqueItems.True

答案 2 :(得分:0)

在我刚刚修改代码以删除最后一个值以及索引号(如果数据是列表的情况下)的情况下,功劳仍然归于@Sunitha。

json_load = json.load(my_keywordfile)
def get_dotted_form(parent,values): 
lines = []
if isinstance(values,dict):
        for key in values.keys():
            # print(keys)
            lines+=get_dotted_form(parent+"."+key, values[key])
elif isinstance(values,list):
        for i,k in enumerate (values):
            # print(keys)
            lines+=get_dotted_form(parent+"."+k, values[i])
else:
        lines.append(parent)
return [line.lstrip('.') for line in lines]    

for x in get_dotted_form("",json_load):
    print(x)
    print('\n')