python中json数据的使用。

dumps和loads也是需要成对使用的,就像c++ new/delete malloc/free一样需要成对使用。

看着像json的字符串,也不一定是json字符串。哈哈。

具体看例子吧。

 1 #coding=utf-8
 2 
 3 import json
 4 
 5 data = {"name":"张三", "age":18, "friend":["王麻子", "李四"]}
 6 print data
 7 print json.dumps(data)
 8 print json.dumps(data, indent=4)    ##设置输出格式
 9 print json.dumps(data, indent=4, ensure_ascii=False)    ##非二进制编码
10 
11 print "*" * 50
12 data_str = json.dumps(data, indent=4, ensure_ascii=False)
13 data_js = json.loads(data_str)
14 print data_js["age"]    ##读取元素
15 print data_js.get("chengshi", "bj") ##如果读取不到可以设置默认值

输出:

Python json模块dumps loads

 

相关文章:

  • 2021-01-25
  • 2021-09-19
  • 2019-10-10
  • 2020-05-12
  • 2019-02-07
  • 2019-11-23
  • 2021-08-03
  • 2018-03-14
猜你喜欢
  • 2018-05-14
  • 2021-09-14
  • 2020-01-31
  • 2019-02-19
  • 2019-03-11
  • 2021-09-14
  • 2020-04-21
  • 2021-09-19
相关资源
相似解决方案