简体   繁体   中英

How to dynamically construct a json object in python

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 ie 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?

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
    }

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