使用python替换json文件中的引号

时间:2019-04-26 21:43:40

标签: python json

如何使用python脚本将json文件中的单引号引起来的双引号。

文件名:strings.json 文件内容

[{'postId':'328e9497740b456154c636349','postTimestamp': '1521543600','pageType': '/home.php:topnews','viewTime': 1521545993647,'user_name': 'windows-super-user','gender': 3,'likes': '8','id': 'ffa1e07529ac917f6d573a','postImg': 1,'postDesc': [753],'origLink': 0,'duration': 0,'timestamp': 9936471521545,'back_time': 1521545993693},{'postId':'15545154c636349','postTimestamp': '547773600',        'pageType': '/home.php:topnews','viewTime': 45993647,'user_name': 'linux user','gender': 3,'likes': '8','id': '695e45a17f6d573a','postImg': 1,'postDesc': [953],'origLink': 0,'duration': 0,'timestamp': 545993647,'back_time': 85993693},{'postId':'9098897740b456154c636349','postTimestamp': '899943600',  'pageType': '/home.php:topnews','viewTime': 1521545993647,'user_name': 'unix_super_user','gender': 3,'likes': '8','id': '917f6d573a695e45affa1e07','postImg': 1,'postDesc': [253],'origLink': 0,'duration': 0,'timestamp': 193647,'back_time': 1521545993693}]

我尝试了下面的代码,但是它不起作用;

with open('strings.json') as f:
    jstr = json.dump(f)
    print(jstr)

预期输出:

[
    {
        "postId":"328e9497740b456154c636349",
        "postTimestamp": "1521543600",
        "pageType": "/home.php:topnews",
        "viewTime": 1521545993647,
        "user_name": "windows-super-user",
        "gender": 3,
        "likes": "8",
        "id": "ffa1e07529ac917f6d573a",
        "postImg": 1,
        "postDesc": [753],
        "origLink": 0,
        "duration": 0,
        "timestamp": 9936471521545,
        "back_time": 1521545993693
    },
    {
        "postId":"15545154c636349",
        "postTimestamp": "547773600",
        "pageType": "/home.php:topnews",
        "viewTime": 45993647,
        "user_name": "linux user",
        "gender": 3,
        "likes": "8",
        "id": "695e45a17f6d573a",
        "postImg": 1,
        "postDesc": [953],
        "origLink": 0,
        "duration": 0,
        "timestamp": 545993647,
        "back_time": 85993693
    }
]

1 个答案:

答案 0 :(得分:2)

单引号对于JSON中的字符串无效,因此就任何解析器而言,该文件都不是JSON。

如果要将所有单引号替换为双引号,请执行以下操作:

# Read in the file contents as text
with open('strings.json') as f:
    invalid_json = f.read()

# Replace all ' with "
valid_json = invalid_json.replace("'", '"')

# Verify that the JSON is valid now and this doesn't raise an exception
json.loads(valid_json)

# Save the modified text back to the file
with open('strings.json.fixed', 'w') as f:
    f.write(valid_json)