Python 在特定位置写入现有json文件

Python 在特定位置写入现有json文件,python,json,python-3.x,Python,Json,Python 3.x,我有一个json文件,其中必须添加一些我从另一个json文件获得的值。问题是,我可以在json末尾添加任何内容,但不能在确切的位置添加。 我的实际json文件是: { "id" : "some-id", "name" : "some-name", "email" : "some@email.com", "config" : { "pipelineConfigs" : [ { "application" : "service1", "pipeline

我有一个json文件,其中必须添加一些我从另一个json文件获得的值。问题是,我可以在json末尾添加任何内容,但不能在确切的位置添加。 我的实际json文件是:

{
  "id" : "some-id",
  "name" : "some-name",
  "email" : "some@email.com",
  "config" : {
    "pipelineConfigs" : [ {
      "application" : "service1",
      "pipelineConfigId" : "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
    }, {
      "application" : "service2",
      "pipelineConfigId" : "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
    } ],
    "applications" : [ "service1", "service2" ],
    "clusters" : [ {
      "account" : "some-account",
      "stack" : "*",
      "detail" : "*",
      "applications" : null
    } ]
  },
  "updateTs" : 1510750871252,
  "createTs" : 1510743534340,
  "lastModifiedBy" : "admin"
}
我正在从另一个json文件获取
service3
另一个id
,需要以以下方式将它们添加到目标json文件中:

       {
      "application" : "service3",
      "pipelineConfigId" : "another-id"
    },
本部分之后:

"config" : {
    "pipelineConfigs" : [
并将
“service3”
添加到
“应用程序”:[“service1”、“service2”],

预期的最终结果:

{
  "id" : "some-id",
  "name" : "some-name",
  "email" : "some@email.com",
  "config" : {
    "pipelineConfigs" : [ {
      "application" : "service1",
      "pipelineConfigId" : "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
    }, {
      "application" : "service2",
      "pipelineConfigId" : "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
    }, {
      "application" : "service3",
      "pipelineConfigId" : "another-id"
    } ],
    "applications" : [ "service1", "service2", "service3" ],
    "clusters" : [ {
      "account" : "some-account",
      "stack" : "*",
      "detail" : "*",
      "applications" : null
    } ]
  },
  "updateTs" : 1510750871252,
  "createTs" : 1510743534340,
  "lastModifiedBy" : "admin"
}

我应该向哪个方向挖掘?

一旦加载了JSON文件,这些结构就是嵌套的Python字典和列表:

import json

data = '''\
{
  "id" : "some-id",
  "name" : "some-name",
  "email" : "some@email.com",
  "config" : {
    "pipelineConfigs" : [ {
      "application" : "service1",
      "pipelineConfigId" : "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
    }, {
      "application" : "service2",
      "pipelineConfigId" : "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
    } ],
    "applications" : [ "service1", "service2" ],
    "clusters" : [ {
      "account" : "some-account",
      "stack" : "*",
      "detail" : "*",
      "applications" : null
    } ]
  },
  "updateTs" : 1510750871252,
  "createTs" : 1510743534340,
  "lastModifiedBy" : "admin"
}'''

D = json.loads(data)
other = {'application':'service3',
         'pipelineconfigId':'another-id'}

# Make the two modifications...
D['config']['pipelineConfigs'].append(other)
D['config']['applications'].append(other['application'])

data = json.dumps(D,indent=2)
print(data)
输出:

{
  "id": "some-id",
  "name": "some-name",
  "email": "some@email.com",
  "config": {
    "pipelineConfigs": [
      {
        "application": "service1",
        "pipelineConfigId": "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
      },
      {
        "application": "service2",
        "pipelineConfigId": "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
      },
      {
        "application": "service3",
        "pipelineconfigId": "another-id"
      }
    ],
    "applications": [
      "service1",
      "service2",
      "service3"
    ],
    "clusters": [
      {
        "account": "some-account",
        "stack": "*",
        "detail": "*",
        "applications": null
      }
    ]
  },
  "updateTs": 1510750871252,
  "createTs": 1510743534340,
  "lastModifiedBy": "admin"
}
a、 py:

注释

  • 我将您的初始json保存在名为initial.json的文件中,我正在使用模块加载该文件
  • 需要做的2件事(加载文件后):
    • 将应用程序名称添加到“现有应用程序”列表中
    • 将应用程序配置添加到现有管道配置列表中
  • 我没有做任何错误检查
输出


这对我有用。我还需要将FINAL写回初始文件。因此,当我运行脚本并打开json文件后,我将看到最终结果。我应该使用json.dumps吗?刚刚添加了代码。可以使用
json.dump
(写入字符串),但使用
json.dump
更容易。我正在写入另一个文件(以避免覆盖原始内容)。将输出文件名更改为,以与输入文件的名称相匹配。这会写入一个文件,但只有一行。如何像以前那样书写?添加了一些缩进。请注意,它不会完全匹配问题中的输入json(“记录”如:
[{
},{
}]
);没关系。但是添加缩进会给我带来一个错误“TypeError:“indent”是一个无效的关键字参数,用于这个函数“thanking@Mark”。它起作用了。但我还需要将其写入初始文件。我应该用什么?
import json
from pprint import pprint as pp

def add_app(obj_dict, app_name, pipeline_config_id):
    new_cfg = {
        "application": app_name,
        "pipelineConfigId": pipeline_config_id,
    }
    obj_dict["config"]["pipelineConfigs"].append(new_cfg)
    obj_dict["config"]["applications"].append(app_name)


def main():
    with open("initial.json") as fin:
        obj = json.load(fin)
    print("INITIAL:\n")
    pp(obj)
    add_app(obj, "service3", "another_id")
    print("\nFINAL:\n")
    pp(obj)
    # EDIT: writing the modified json to file
    with open("final.json", "w") as fout:
        json.dump(obj, fout, indent="  ")


if __name__ == "__main__":
    main()
c:\Work\Dev\StackOverflow\q47345368>"c:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" a.py
INITIAL:

{'config': {'applications': ['service1', 'service2'],
            'clusters': [{'account': 'some-account',
                          'applications': None,
                          'detail': '*',
                          'stack': '*'}],
            'pipelineConfigs': [{'application': 'service1',
                                 'pipelineConfigId': 'd2eb526c-839b-41b3-b59c-f86db6eebb4e'},
                                {'application': 'service2',
                                 'pipelineConfigId': 'f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7'}]},
 'createTs': 1510743534340,
 'email': 'some@email.com',
 'id': 'some-id',
 'lastModifiedBy': 'admin',
 'name': 'some-name',
 'updateTs': 1510750871252}

FINAL:

{'config': {'applications': ['service1', 'service2', 'service3'],
            'clusters': [{'account': 'some-account',
                          'applications': None,
                          'detail': '*',
                          'stack': '*'}],
            'pipelineConfigs': [{'application': 'service1',
                                 'pipelineConfigId': 'd2eb526c-839b-41b3-b59c-f86db6eebb4e'},
                                {'application': 'service2',
                                 'pipelineConfigId': 'f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7'},
                                {'application': 'service3',
                                 'pipelineConfigId': 'another_id'}]},
 'createTs': 1510743534340,
 'email': 'some@email.com',
 'id': 'some-id',
 'lastModifiedBy': 'admin',
 'name': 'some-name',
 'updateTs': 1510750871252}