简体   繁体   中英

How to get nested key value from a json file

I have the following structure:

{
  "$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
    }
  }
}

which is saved in a file called "my_keywordfile". and I want to have something like:

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

Here is the code that I have:

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)

But it gives me this error:

TypeError: must be str, not list

Anyone knows how to fix it? it works fine till this line:

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

This section, prints out keys and their values at the first level. But it seems there is something wrong with the rest of the code!

You need this line to be printing x not value and you can remove the for i in range(0, len(value) > i):

for x in value:
    print(key+'.'+x)
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)

Output

$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

The credit still goes to @Sunitha as I just modified the code to remove the last values, as well as, the index number in case the data is a list.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM