zoukankan      html  css  js  c++  java
  • python3 之 格式化json

    import json
    
    json_string = None
    
    with open("json_file.json") as f:
        json_string = f.read()
    try:
        parsed_json = json.loads(json_string)
        formatted_json = json.dumps(parsed_json, indent = 4,sort_keys=True)
        with open("json_file.json","w") as f:
            f.write(formatted_json)
    except Exception as e:
        print(repr(e))

    Parameter indent  decides the number of spaces to use for indentation.  

    Parameter sort_keys decides whether the keys in formatted JSON should be in sorted order or not. Default value is False.    


    Bonus: You can pretty-print the small JSON string directly at command terminal without using python script file. Use below line of code.

    echo '{"first_name": "Anurag", "last_name": "rana"}' | python -m json.tool
  • 相关阅读:
    关于闭包的一些知识
    浏览器解析JavaScript原理(1)
    函数作用域及函数表达式
    jquery
    前端常用插件
    Git及GitHub
    angular框架
    express
    ES6基础
    Node.js相关总结
  • 原文地址:https://www.cnblogs.com/zxpo/p/10011078.html
Copyright © 2011-2022 走看看