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

标签 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
    }
]

最佳答案

单引号对于 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)

关于python - 使用python替换json文件中的引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55875262/

相关文章:

python - 故障训练 SVM(scikit-learn 包)

javascript - 根据项目属性值在数组中查找某些项目的最佳方法是什么?

python - 从 json 模式中获取必填字段

python - 使用 numpy loadtxt 时添加 'b' 字符

python - Pytest - 如何从命令行覆盖 fixture 参数列表?

python - 生成列表的随机排列

c# - 将一个分层列表投影到另一个具有匿名类型(或动态)的分层列表?

javascript - 如何使用 Reactjs 显示 xml 数据

java - 无法设置我的 RecyclerView 以显示来自 API 回调的完整数据

python - AWS Glue 限制输入大小