简体   繁体   中英

How to extract data from variable Path in JSON files using Python

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]

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.

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

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