编辑JSON文件

时间:2019-04-22 13:53:21

标签: python json

我想编辑JSON转储文件。 示例:

[
    "Date",
    "17/04/2019",
    "Skill",
    "Travis",
    "Repository",
    "27,699 repository results"
][
    "Date",
    "17/04/2019",
    "Skill",
    "Kotlin",
    "Repository",
    "55,752 repository results"
]

我想要这样:

[
    "Date",
    "17/04/2019",
    "Skill",
    "Travis",
    "Repository",
    "27,699 repository results"
],[
    "Date",
    "17/04/2019",
    "Skill",
    "Kotlin",
    "Repository",
    "55,752 repository results"
]

1 个答案:

答案 0 :(得分:0)

使用str.replace()

someFile.json:

[
    "Date",
    "17/04/2019",
    "Skill",
    "Travis",
    "Repository",
    "27,699 repository results"
][
    "Date",
    "17/04/2019",
    "Skill",
    "Kotlin",
    "Repository",
    "55,752 repository results"
]

因此

with open('someFile.json', 'r') as fp:
    content = fp.readlines()        
    content = [l.strip() for l in content if l.strip()]
    for line in content:
       if '][' in line:
           print(line.replace('][','],['))
       else:
           print(line)

输出

[
"Date",
"17/04/2019",
"Skill",
"Travis",
"Repository",
"27,699 repository results"
],[
"Date",
"17/04/2019",
"Skill",
"Kotlin",
"Repository",
"55,752 repository results"
]

编辑

一个看起来像json的文件应该是:

someFile.json:

[
    {
        "date": "Date",
        "dt": "17/04/2019",
        "skill":  "Skill",
        "travel": "Travis",
        "repo": "Repository",
        "dat": "27,699 repository results"
    }
][
    {
        "date": "Date",
        "dt": "17/04/2019",
        "skill":  "Skill",
        "travel": "Kotlin",
        "repo": "Repository",
        "dat": "2327,699 repository results"
    }
]

因此

import json

with open('someFile.json', 'r') as file:
    content = file.read()
    clean = content.replace('][', ',')  # cleanup here
    json_data = json.loads(clean)

print(json_data)

输出

[
  {'date': 'Date', 'dt': '17/04/2019', 'skill': 'Skill', 'travel': 'Travis', 'repo': 'Repository', 'dat': '27,699 repository results'}, 
  {'date': 'Date', 'dt': '17/04/2019', 'skill': 'Skill', 'travel': 'Kotlin', 'repo': 'Repository', 'dat': '2327,699 repository results'}
]