在文件中添加行

时间:2018-01-26 12:25:04

标签: sed grep cut

我有一个文件:

"struct_personnal": [
    {
        "id": "1",
        "name": "Mathieu"
    }
],
"struct_hospital": [
    {
        "id": "9",
        "geo": "chamb",
        "nb": ""
    },
    {
        "id": "",
        "geo": "jsj",
        "nb": "SMITH"
    },
    {
        "id": "10",
        "geo": "",
        "nb": "12"
    },
    {
        "id": "2",
        "geo": "marqui",
        "nb": "20"
    },
    {
        "id": "4",
        "geo": "oliwo",
        "nb": "1"
    },
    {
        "id": "1",
        "geo": "par",
        "nb": "5"
    }
]

我想得到一个块的最后一行“}”的行数(struct_hospital,struct_personal等) 该文件可能包含其他信息。

如果我想在块“struct_personnal”的末尾添加文本,则输出为:

"struct_personnal": [
    {
        "id": "1",
        "name": "Mathieu"
    }
   ##############
   #My text here#
   ##############
],
"struct_hospital": [
    {
        "id": "9",
        "geo": "chamb",
        "nb": ""
    },
    {
        "id": "",
        "geo": "jsj",
        "nb": "SMITH"
    },
    {
        "id": "10",
        "geo": "",
        "nb": "12"
    },
    {
        "id": "2",
        "geo": "marqui",
        "nb": "20"
    },
    {
        "id": "4",
        "geo": "oliwo",
        "nb": "1"
    },
    {
        "id": "1",
        "geo": "par",
        "nb": "5"
    }
]

与struct_hospital相同

怎么样?我不明白...... 谢谢你!

1 个答案:

答案 0 :(得分:1)

如果它是一个json文件,那么我会使用python。只需加载文件并使用json.load函数将json内容转换为python dict。

import json

content = None
with open('path/to/input_file') as f:
    content = json.load(f)

#change the key to struct_hospital if you want to append inside  struct_hospital block
content['struct_personnal'].append({'hi': 'my new text'})

with open('path/to/input_file', 'w') as w:
    json.dump(content, w)