zoukankan      html  css  js  c++  java
  • Python--json处理

    import json

    # json串就是字符串
    d = {
    'car': {'color': 'red', 'price': '100', 'count': 50},
    'car1': {'color': 'red', 'price': '100', 'count': 50},
    'car2': {'color': 'red', 'price': '100', 'count': 50},
    '汽车': {'color': 'red', 'price': '100', 'count': 50},
    }
    res = json.dumps(d, indent=4, ensure_ascii=False) # 把list/字典转为json,indent多少缩进,ensure_ascii 可以显示中文
    print(res)

    with open('f1', 'w', encoding='utf-8') as f:
    f.write(res)

    with open('f1', encoding='utf-8') as f:
    res = f.read()
    dict_res = json.loads(res) # 把json变为python的数据类型
    print(type(dict_res))
    print(dict_res)

    # json中必须为双引号

    # 自动的帮你写入文件,第一个参数是数据,第二个是文件对象
    with open('f1', 'w', encoding='utf-8') as f:
    json.dump(d, f, ensure_ascii=False, indent=4)

    # 自动的帮你读文件
    with open('f1', encoding='utf-8') as f:
    print(json.load(f))
  • 相关阅读:
    MySQL(一)
    HTML基础
    python函数基础
    常用的模块
    面向对象进阶
    定制自己的数据类型
    Shell篇之AWK
    MATLAB如何实现傅里叶变换FFT?有何物理意义?
    傅里叶分析
    2018年度关键词
  • 原文地址:https://www.cnblogs.com/wangsilei/p/8317888.html
Copyright © 2011-2022 走看看