Fix unquoted keys in JSON-like file so that it uses correct JSON syntax

前端 未结 3 1582
野趣味
野趣味 2021-01-17 02:41

I have a very large JSON-like file, but it is not using proper JSON syntax: the object keys are not quoted. I\'d like to write a script to fix the file, so that I can load

3条回答
  •  鱼传尺愫
    2021-01-17 02:59

    Rather than a potentially fragile regex solution, you can take advantage of the fact that while your log file isn't valid JSON, it is valid YAML. Using the PyYAML library, you can load it into a Python data structure and then write it back out as valid JSON:

    import json
    import yaml
    
    with open("original.log") as f:
        data = yaml.load(f)
    
    with open("jsonified.log", "w") as f:
        json.dump(data, f)
    

提交回复
热议问题