首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从json文件中获取嵌套键值

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

Stack Overflow用户
提问于 2018-07-03 04:32:01
回答 2查看 243关注 0票数 0

我有以下结构:

代码语言:javascript
复制
{
  "$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“的文件中。我想要像这样的东西:

代码语言:javascript
复制
$schema.http,
type.object,
...,
**properties.primaryId.$ref,
properties.primaryId.description**

下面是我的代码:

代码语言:javascript
复制
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)

但是它给了我这个错误:

代码语言:javascript
复制
TypeError: must be str, not list

有人知道怎么修吗?它工作得很好,直到下面这行:

代码语言:javascript
复制
for key, value in json_load.items():
        print((key,value))

本节将在第一级打印出关键字及其值。但是看起来其余的代码有问题!

EN

回答 2

Stack Overflow用户

发布于 2018-07-03 04:37:07

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

代码语言:javascript
复制
for x in value:
    print(key+'.'+x)
票数 0
EN

Stack Overflow用户

发布于 2018-07-03 22:56:43

这仍然归功于@Sunitha,因为我刚刚修改了代码以删除最后的值,以及在数据是列表的情况下的索引号。

代码语言:javascript
复制
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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51143356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档