Home > Net >  python extract key from json file doesn't work
python extract key from json file doesn't work

Time:06-02

I am new to python and I am using python 3.9.13 trying to extract values from existing keys in a json file. I know that json.load() function outputs a dictionary so at the last part of my code I am searching in a dictionary.

Here is my python code:

import os
import json

with open('./output.json', 'r') as f:
  data = json.load(f)

values= []

if "created" in data:
    print("Key found!")
    print ("Version: ", data["version"], "created at: ", data["created"])
    values.append(data["version"])

print(values)

Here is the output.json file I am reading from:

{
  "section1": [
    {
      "name": "name1",
      "version": "1.0.0",
      "description": "",
      "apiVersion": "v2",
      "appVersion": "1.0.22",
      "type": "application",
      "created": "2022-05-03T11:20:45Z"
    },
    {
      "name": "name1",
      "version": "1.0.1",
      "description": "",
      "apiVersion": "v2",
      "appVersion": "1.0.22",
      "type": "application",
      "created": "2022-04-20T13:55:16Z"
    }
  ],
  "section2": [
    {
      "name": "name2",
      "version": "2.0.0",
      "description": "",
      "apiVersion": "v2",
      "appVersion": "1.0.17",
      "type": "application",
      "created": "2022-01-25T07:58:09Z"
    },
    {
      "name": "name2",
      "version": "2.0.1",
      "description": "",
      "apiVersion": "v2",
      "appVersion": "1.0.17",
      "type": "application",
      "created": "2022-01-18T07:08:38Z"
    }
  ]
}

I expect my array values to be:

[1.0.0, 1.0.1, 2.0.0, 2.0.1]

But my output is an empty array and I cannot figure out why.

Would appreciate your help!

CodePudding user response:

You're not respecting the dictionnary hierarchy, when you call a key in a dict, it doesn go through all the levels of that dictionnary ... here's a changed version of your code that does the job :

import os
import json

with open('./output.json', 'r') as f:
    json_dict = json.load(f)

values= []

for section in json_dict.values():
    for el in section:
        print("Key found!")
        print ("Version: ", el["version"], "created at: ", el["created"])
        values.append(el["version"])

print(values) 

output :

Key found!
Version:  1.0.0 created at:  2022-05-03T11:20:45Z
Key found!
Version:  1.0.1 created at:  2022-04-20T13:55:16Z
Key found!
Version:  2.0.0 created at:  2022-01-25T07:58:09Z
Key found!
Version:  2.0.1 created at:  2022-01-18T07:08:38Z
['1.0.0', '1.0.1', '2.0.0', '2.0.1']

CodePudding user response:

First, assuming data is a dict type, populated from JSON as above:

data = json.load(f)

Then the simplest way to achieve the desired output, would be to use a nested list comprehension as follows:

>>> [dct['version'] for lst in data.values() for dct in lst]
['1.0.0', '1.0.1', '2.0.0', '2.0.1']

Note that the list comprehension above is basically the equivalent of two for loops:

result = []
for lst in data.values():
    for dct in lst:
        result.append(dct['version'])

If you need to specifically check for the presence of a "created" key, or if you need to validate that you're iterating over list and dict types for example, you can instead use this approach:

result = [dct['version'] for lst in data.values() if isinstance(lst, list)
          for dct in lst if isinstance(dct, dict) and 'created' in dct]

CodePudding user response:

Your code could be like this:

import os
import json

with open('./output.json', 'r') as f:
  data = json.load(f)

values= []
for section in data:
    for x in range(len(data.values())):
        if "created" in data[section][x]:
            print("Key found!")
            print ("Version: ", data[section][x]["version"], "created at: ", data[section][x]["created"])
            values.append(data[section][x]["version"])

print(values)
  • Related