Home > Enterprise >  How to dynamically construct a json object in python
How to dynamically construct a json object in python

Time:08-03

I have a json object which looks like the following:

body = {
    "to": tableId,
    "data": [
        {
            fieldId1: {
                "value": fieldValue
            },
            fieldId2: {
                "value": fieldValue2
            }
        }
    ],
    "fieldsToReturn": [
        fieldId,
        fieldId2
    ]
}

I need a way to dynamically make this json object such that the number of fields i.e. fieldIds is passed into the function as well as the "value" of the fieldId. The "to": tableId should be part of the json object. Imagine if I had the columns of dataframe. Then the fieldIds would correspond to the number of columns and the values for the fieldIds would correspond to the name of the columns. I want to populate a json object for any given number of columns with their own column names. How would I do this in python?

CodePudding user response:

Use zip() and a dictionary comprehension to combine the field IDs and values into the list of a dictionary.

def make_body(tableid, field_ids, field_values):
    return {
        "to": tableid,
        "data": [ {id: {"value": value} for id, value in zip(field_ids, field_values)}],
        "fieldsToReturn": field_ids
    }
  • Related