在json中找到特定的键,并使用python将父对象插入其中

ckx4rj1h  于 2023-08-08  发布在  Python
关注(0)|答案(2)|浏览(108)

我试图在json中插入父对象,但它将其插入顶部,但我想插入JSON中的特定键之后。我尝试添加下面的代码,但它在顶部插入父(我明白,因为它是父,它将被插入在顶部,但我想在特定的关键字之前插入,在这种情况下,关键字是“模式”:

with open ("myfile.json", 'r') as f:
    myjson = json.load(f)

myjson = {'Main Parent': myjson}

字符串
基本上我想插入“版本”:“模式”之前

"versions":{
           "pattern": {
             "provider": "abc",
             "schema": "xyz" 
           },
           "baseline":{
              "version" : "dev"
           }
       }


输入json文件

{
          "target": {
             "Name": "abc",
             "Occupation": "xyz" 
           },
           "properties":{
              "env" : "dev"
           },
           "use_it": "xyz",
           "pattern": {
             "provider": "abc",
             "schema": "xyz" 
           },
           "baseline":{
              "version" : "dev"
           }   
    }


预期输出json文件
输入json文件

{
          "target": {
             "Name": "abc",
             "Occupation": "xyz" 
           },
           "properties":{
              "env" : "dev"
           },
           "use_it": "xyz",
        "versions":{
           "pattern": {
             "provider": "abc",
             "schema": "xyz" 
           },
           "baseline":{
              "version" : "dev"
           }
       }   
    }

dluptydi

dluptydi1#

这样的东西对你有用吗?

import json

with open ("myfile.json", 'r') as f:
    myjson = json.load(f)

# Add any top level keys you want to move into the `versions` key
versions_keys = [
    "pattern", "baseline"
]

myjson["versions"] = {}

for version_key in versions_keys:
    key = myjson.pop(version_key)
    myjson["versions"][version_key] = key

myjson = {'Main Parent': myjson}

print(json.dumps(myjson, indent=4))

字符串
pop方法从dict中删除键并返回其值。
我们存储该值并将其放回新的“versions”键下。
输出量:

{
    "Main Parent": {
        "target": {
            "Name": "abc",
            "Occupation": "xyz"
        },
        "properties": {
            "env": "dev"
        },
        "use_it": "xyz",
        "versions": {
            "pattern": {
                "provider": "abc",
                "schema": "xyz"
            },
            "baseline": {
                "version": "dev"
            }
        }
    }
}

vulvrdjw

vulvrdjw2#

是的,你可以动态地从versions字典中获取键,并将它们插入到JSON中的“pattern”键之前!
看看这个:

import json

with open("myfile.json", "r") as f:
    myjson = json.load(f)

versions = {
    "pattern": {
        "provider": "abc",
        "schema": "xyz"
    },
    "baseline": {
        "version": "dev"
    }
}

index = list(myjson).index("pattern")

updated_json = {}

for i, (key, value) in enumerate(myjson.items()):
    if key == "pattern":
        updated_json["versions"] = versions
    updated_json[key] = value

with open("myfile.json", "w") as f:
    json.dump(updated_json, f, indent=4)

字符串
正如您所看到的,versions字典是用所需的键值对定义的,并且在通过原始JSON迭代期间,当遇到pattern键时,versions字典会被插入到它之前!

相关问题