1

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?

0

1 Answer 1

2

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
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.