zoukankan      html  css  js  c++  java
  • 严格的JSON格式

    用Python处理/生成JSON文件

    先看个python list/array:

    my_list = [
    {"Jerry": {"job": "comedian", "age": 34, "married": True,},},
    {"Elaine": {"job": "housewife", "age": 32, "married": False,},}
    ]
    print(my_list)

    运行结果为:

    [{'Jerry': {'job': 'comedian', 'age': 34, 'married': True}}, {'Elaine': {'job': 'housewife', 'age': 32, 'married': False}}]

    注意看区别:

    一、双引号,变成了单引号;

    二、原代码my_list中,在True,False后面,我特地添加了两个额外的逗号,,而这些逗号在python运行后,被忽略了。所以以后建议不要加。而且,如果加了,在用JSON load这个list时,会报错

    把上面的运行结果

    [{'Jerry': {'job': 'comedian', 'age': 34, 'married': True}}, {'Elaine': {'job': 'housewife', 'age': 32, 'married': False}}]

    保存到source.json文件中,注意把True,False改为true, false

    import json
    with open("source.json") as f:
        data = json.load(f)
    
    with open("target.json", 'w', encoding='utf-8') as file:
        json.dump(data, file, indent=4, ensure_ascii=False)

    运行上面的代码,生成的target.json文件里,会得到:

    [
        {
            "jerry": {
                "job": "comedian",
                "age": 34,
                "married": true
            }
        },
        {
            "Elaine": {
                "job": "housewife",
                "age": 32,
                "married": false
            }
        }
    ]
  • 相关阅读:
    Swap 2 Variables in Python
    Python Static Method
    Longest Palindromic Substring-Dynamic Programing
    Config Static IP Address manually in Ubuntu
    network FAQ
    [Python] Send emails to the recepients specified in Message["CC"]
    Rare But Powerful Vim Commands.
    主机名 域名 网站名 URL
    Extracts
    关于hibernate一对一配置
  • 原文地址:https://www.cnblogs.com/profesor/p/12981554.html
Copyright © 2011-2022 走看看