写入特定位置的现有json文件

时间:2017-11-17 07:27:21

标签: python json python-3.x

我有一个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文件获取service3another-id需要以这种方式将它们添加到目标json文件中:

       {
      "application" : "service3",
      "pipelineConfigId" : "another-id"
    },

此部分之后:

"config" : {
    "pipelineConfigs" : [

并将"service3"添加到"applications" : [ "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"
}

我应该挖哪个方向?

2 个答案:

答案 0 :(得分:1)

一旦你加载了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"
}

答案 1 :(得分:0)

a.py

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()

备注

  • 我将您的初始json保存在一个名为 initial.json 的文件中,我正在使用[Python]: json — JSON encoder and decoder模块加载
  • 需要做的2件事(加载文件后):
    • 将应用程序名称添加到现有应用程序列表
    • 将应用程序配置广告到现有的管道配置列表
  • 进行任何错误检查

<强>输出

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}