Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map and Combine JSON objects in Python

Tags:

python

json

Still learning Python and trying to combine 2 JSON objects.

Primary Data Set:

{
    "form-fields": [
        {"type": "text", "x-position": 0, "y-position": 0, "field": "buyer-1"},
        {"type": "text", "x-position": 0, "y-position": 10, "field": "buyer-2"}
    ]
}

Secondary Data Set:

{
    "form-data": [
        {"field": "buyer-1", "value": "John Smith"},
        {"field": "buyer-2", "value": "Susan Smith"}
    ]
}

Intended Result: With "value" appended to the original object.

{
    "form-fields": [
        {"type": "text", "x-position": 0, "y-position": 0, "field": "buyer-1", "value": "John Smith"},
        {"type": "text", "x-position": 0, "y-position": 10, "field": "buyer-2", "value": "Susan Smith"}
    ]
}
like image 990
Parker Avatar asked Jul 07 '26 13:07

Parker


1 Answers

I assume that the fields are not in order between primary and secondary. The plan is to create a dictionary call update where key=field and value=secondary's value. Then update the primary.

primary = {
    "form-fields": [
        {"type": "text", "x-position": 0, "y-position": 0, "field": "buyer-1"},
        {"type": "text", "x-position": 0, "y-position": 10, "field": "buyer-2"}
    ]
}

secondary = {
    "form-data": [
        {"field": "buyer-1", "value": "John Smith"},
        {"field": "buyer-2", "value": "Susan Smith"}
    ]
}

update = {
    record["field"]: record["value"]
    for record in secondary["form-data"]
}
# update is {'buyer-1': 'John Smith', 'buyer-2': 'Susan Smith'}

for record in primary["form-fields"]:
    if record["field"] in update:
        record["value"] = update[record["field"]]

The result is primary to become

{
    "form-fields": [
        {
            "type": "text",
            "x-position": 0,
            "y-position": 0,
            "field": "buyer-1",
            "value": "John Smith"
        },
        {
            "type": "text",
            "x-position": 0,
            "y-position": 10,
            "field": "buyer-2",
            "value": "Susan Smith"
        }
    ]
}
like image 64
Hai Vu Avatar answered Jul 10 '26 02:07

Hai Vu