Home > other >  assigning a json dictionary key value to a variable
assigning a json dictionary key value to a variable

Time:08-26

I have a json with the following structure.

{
    "source": {
        "excelsheetname": {
            "convert_to_csv": "True",
            "tgt_folder": "archieve/datetime=",
            "brand": "chicken",
            "sheets": {
                "sheet1":{
                    "headers": 5,
                    "columns": 1
                },
                "sheet2": {
                    "headers": 3,
                    "columns": 2
                },
                "sheet3": {
                    "headers": 5,
                    "columns": 3
                },
                "sheet4": {
                    "headers": 3,
                    "columns": 2
                }
            }
        }

What I am trying to do is create a for loop assign the sheet headers and columns to a variable.

This is what my code looks like:

for i in config['source']['excelsheetname']['sheets'][i]:
    if i == "headers":
        value = i['headers']

But this code doesnt work, as I keep getting the "TypeError: string indices must be integers"

CodePudding user response:

First, you want to parse the JSON into a Python dictionary:

import json
config_str = """
{
    "source": {
        "excelsheetname": {
            "convert_to_csv": "True",
            "tgt_folder": "archieve/datetime=",
            "brand": "chicken",
            "sheets": {
                "sheet1":{
                    "headers": 5,
                    "columns": 1
                },
                "sheet2": {
                    "headers": 3,
                    "columns": 2
                },
                "sheet3": {
                    "headers": 5,
                    "columns": 3
                },
                "sheet4": {
                    "headers": 3,
                    "columns": 2
                }
            }
        }
    }
}
"""
config = json.loads(config_str)

From your question, I understood that you want to get a list of the headers and a list of the columns. When you iterate over a dictionary in Python, you have two values: the key and the value. We can use the values() method to iterate only over the values. Your code iterates over an expression that includes the loop variable, which doesn't make sense, as the variable doesn't exist until then. You could use a simple for loop to get what you want:

for sheet in config["source"]["excelsheetname"]["sheets"].values():
    headers = sheet["headers"]
    columns = sheet["columns"]
    # Processing
    print(headers   columns) # Just an example of processing

CodePudding user response:

Not quiet sure if i get your question right but this will deliever the integer at key "headers" and "columns" for every sheet in sheets

    for i in config['source']['excelsheetname']['sheets'].keys():
        
        if "header" in config['source']['excelsheetname']['sheets'][i].keys():
            header_value= config['source']['excelsheetname']['sheets'][i]["headers"]
            print(header_value) # store it or do whatever you want
        if "columns" in config['source']['excelsheetname']['sheets']
            column_value = config['source']['excelsheetname']['sheets'][i]["columns"]
            print(column_value ) # store it or do whatever you want
  • Related