首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python中映射和组合JSON对象

在Python中映射和组合JSON对象
EN

Stack Overflow用户
提问于 2022-06-11 17:55:19
回答 2查看 87关注 0票数 2

仍然在学习Python并试图组合2个JSON对象。

主数据集:

代码语言:javascript
复制
{
    "form-fields": [
        {"type": "text", "x-position": 0, "y-position": 0, "field": "buyer-1"},
        {"type": "text", "x-position": 0, "y-position": 10, "field": "buyer-2"}
    ]
}

辅助数据集:

代码语言:javascript
复制
{
    "form-data": [
        {"field": "buyer-1", "value": "John Smith"},
        {"field": "buyer-2", "value": "Susan Smith"}
    ]
}

预期的结果:将"value“附加到原始对象的

代码语言:javascript
复制
{
    "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"}
    ]
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-06-11 18:06:38

我假定这些字段在主字段和次字段之间没有顺序。计划是创建一个字典调用update,其中key=field和value =备用值。然后更新主服务器。

代码语言:javascript
复制
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"]]

结果是primary变成了

代码语言:javascript
复制
{
    "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"
        }
    ]
}
票数 3
EN

Stack Overflow用户

发布于 2022-06-11 18:02:39

假设长度和索引在两本字典中是相同的,

代码语言:javascript
复制
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)

合并字典的示例代码

代码语言:javascript
复制
marks = {'Physics':67, 'Maths':87}
internal_marks = {'Practical':48}

marks.update(internal_marks)


print(marks)

# Output: {'Physics': 67, 'Maths': 87, 'Practical': 48}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72586702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档