Home > database >  Read json key and value as a variables to pass to another function in python
Read json key and value as a variables to pass to another function in python

Time:03-09

I have a json config file like this

{
    "sources":[
        {
            "name":"tbl1",
            "var":"L100",
            "query":"select c1,c2 from tbl1 where c1=L100"
        },
        {
            "name":"tbl2",
            "var":"M00",
            "query":"select c1,c2 from tbl1 where c1=M00"
        },
    ]
}

I would like to read name, var and query and send key and value to other python function for next processing.

Can anyone please how to write the script? I have tried below code and could not to capture the values properly.

import json
with open('file.json', "r") as myfile:
    json_data = json.load(myfile)
    for e, v in json_data.items():
        for key, val in v:
            print(val)

Expected: Read the json data (name, var and query) value and pass to python function.

  • read json
  • capture values corresponds to first, second records, etc...
  • pyfun(name, var, query). In this function I am going to use these values for further procedure.

CodePudding user response:

You can directly get the sources key then iterate with each dictionary and get the required keys

for x in json_data['sources']:
    name, var, query = x['name'], x['var'], x['query']
    # do something
  • Related