Home > Back-end >  How to extract data from variable Path in JSON files using Python
How to extract data from variable Path in JSON files using Python

Time:02-23

I have to extract variable data from a json file, where the path is not a constant.

Here's my code

import json

JSONFILE="output.json"

jsonf = open(JSONFILE, 'r', encoding='utf-8')

with jsonf as json_file:
    data = json.load(json_file)
    print(data["x1"]["y1"][0])

The json file

{
  "x1" : {
    "y1" : [
      {
        "value" : "v1",
        "type" : "t1",
   }
    ]
  },
  "x2" : {
    "y2" : [
      {
       "value" : "v2",
       "type" : "t2",
      }
    ],
}
}

I want to extract all the values not only [x1][y1][value]

CodePudding user response:

All the values should be stored in the data, and they datatype is a dictionary. It's up to you what you want to "index" and obtain. Learn more about dictionaries in Python 3: https://docs.python.org/3/tutorial/datastructures.html#dictionaries

Feel free to ask further questions.

CodePudding user response:

Use for loop to iterate over the dictionary

import json

JSONFILE="output.json"

jsonf = open(JSONFILE, 'r', encoding='utf-8')

with jsonf as json_file:
    data = json.load(json_file)
    for key in data.keys():
       for key2 in data[key].keys():
          print(data[key][key2])
  • Related