Home > Mobile >  Read nested Json File and fetch the required field
Read nested Json File and fetch the required field

Time:08-11

I have the following json file, Need to loop over to fetch the company and its file.

data.json

[
    {
      "count": 0,
      "company": "abc",
      "state": {
        "city": {}
      },
      "name": "Techno",
      "age": 17,
      "file": "cubix.so"
    },
    {
        "count": 12,
        "company": "def",
        "state": {
          "city": {}
        },
        "name": "Uni",
        "age": 17,
        "file": "cyp.so"
      },
      {
        "count": 22,
        "company": "ghi",
        "state": {
          "city": {}
        },
        "name": "unicorn",
        "age": 17,
        "file": "omg.so"
      }  
]

Need to loops through json file and print the file with its company.

import json
import sys
        
f=open('data.json')
print(json.dumps(output))

Expected Output: file with respect to company

CodePudding user response:

Use json.loads() to load from JSON content and context managers while working with files:

import json

with open('data.json') as file:
    data = json.loads(file.read())
    for obj in data:
        print(obj['company'], obj['file'])

Output:

abc cubix.so
def cyp.so
ghi omg.so

CodePudding user response:

After reading the file, you could use json.load() to load the object, which is a list. Then you can iterate over the list and print the respective keys 'company' and 'file'

import json

f = open('data.json')
for e in json.load(f):
    print(e['company'], e['file'])
f.close()

output

abc cubix.so
def cyp.so
ghi omg.so
  • Related