zoukankan      html  css  js  c++  java
  • python json

    json 是一种轻量级的数据交换格式。它基于 ECMAScript 规范的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

    使用 JSON 函数需要导入 json 库:import json

    函数描述
    json.dumps 将 Python 对象编码成 JSON 字符串
    json.loads 将已编码的 JSON 字符串解码为 Python 对象


    Python 编码为 JSON 类型转换对应表:

    PythonJSON
    dict object
    list, tuple array
    str string
    int, float, int- & float-derived Enums number
    True true
    False false
    None null

    JSON 解码为 Python 类型转换对应表:

    JSONPython
    object dict
    array list
    string str
    number (int) int
    number (real) float
    true True
    false False
    null None

    实例将python数据结构转化为json         json.dumps():

     1 import json
     2 
     3 # Python 字典类型转换为 JSON 对象
     4 data = {
     5     'a' : 1,
     6     'b' :'你好',
     7     'c' :'hello'
     8 }
     9 
    10 json_str = json.dumps(data)
    11 print ("Python 原始数据:", repr(data))
    12 print ("JSON 对象:", json_str)

    Python 原始数据: {'a': 1, 'c': '祝你快乐', 'b': '你好'}
    JSON 对象: {"a": 1, "c": "u795du4f60u5febu4e50", "b": "u4f60u597d"}

    将json对象转化为python词典       json.loads():

    将下面代码加入到上面中

    data2 = json.loads(json_str)
    print ("data2['b']: ", data2['b'])
    print ("data2['c']: ", data2['c'])

    结果:

    data2['c']: 祝你快乐
    data2['b']: 你好

    如果你要处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据。例如:

    1 # 写入 JSON 数据
    2 with open('data.json', 'w') as f:
    3     json.dump(data, f)
    4 
    5 # 读取数据
    6 with open('data.json', 'r') as f:
    7     data = json.load(f)
  • 相关阅读:
    Cocostudio学习笔记(2) Button + CheckBox
    Oracle会话及连接数优化
    linux zip压缩和解压的各种操控
    Linux select 机制深入分析
    算法的时间复杂度
    findmaven的英文版本号上线了
    XML高速入门
    spring xml properties split with comma for list
    There is an error in invoking javac. A full JDK (not just JRE) is required
    [Swift]LeetCode134. 加油站 | Gas Station
  • 原文地址:https://www.cnblogs.com/jjj-fly/p/6861612.html
Copyright © 2011-2022 走看看