Home > Software design >  Map and Combine JSON objects in Python
Map and Combine JSON objects in Python

Time:06-12

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"}
    ]
}

CodePudding user response:

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"
        }
    ]
}

CodePudding user response:

Assuming length and index will be same in both dictionaries,

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"}
    ]
}

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

pl = primary.get("form-fields")
sl = sec.get("form-data")

for index, prim_val in enumerate(pl):
    sec_val = sl[index]
    prim_val.update(sec_val)
    
print(primary)

Sample code for merging dictionaries

marks = {'Physics':67, 'Maths':87}
internal_marks = {'Practical':48}

marks.update(internal_marks)


print(marks)

# Output: {'Physics': 67, 'Maths': 87, 'Practical': 48}
  • Related