程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

Python 的json标准库使用方法

发布于2019-12-07 22:52     阅读(1454)     评论(0)     点赞(5)     收藏(5)


目录

json的官网:

1 json化成字符串

2 解析json


 

json的官网:

包含所有语言  http://json.org/

注意: socket编程中传送的数据只能是基本数据类型,int float str无人船演示的时候传送个numpy形式结果出错了

用法参考下面网址:

https://blog.csdn.net/liangxy2014/article/details/78985057

1 json化成字符串

注意:ndarray 数据类型有一个方法 tolist() 这个方法看似没用,这里起到了关键作用:json不能传入ndarray类型,必须传入Python原来的列表类型,这里的tolist()方法起到了关键作用,曾经试过list() 强制类型转换,不好用,这能使用这个方法。

  1. json.dumps(【字典或者列表类型】)
  2. #1 json化的同时具有缩进功能,indent的数值,代表缩进的位数,indent英文意思就是缩排的功能
  3. temp = json.dumps(【字典或者列表类型】,indent=4)
  4. #2 返回的字符串按照索引排序
  5. json.dumps(【字典或者列表类型】, sort_keys=True) # '{"a": 0, "b": 0, "c": 0}'
  6. #3 注意转义字符的使用
  7. json.dumps("\"foo\bar") # "\"foo\bar"
  8. #4 去掉多余的空格,在传输数据时候越精简越好,
  9. json.dumps(data, separators=(',',':'))
  10. #5 输出真正的中文需要指定ensure_ascii=False,如果不指定这个参数,那么就是ascii码,而ascii码根本就没有中文,所以出来就是看不懂的东西
  11. json.dumps('凉凉', ensure_ascii=False)

'''帮助文档
json. dumps ( obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw )
Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is false, the result may contain non-ASCII characters and the return value may be a unicode instance.
The arguments have the same meaning as in dump().
Note
Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.
'''

 

2 解析json

  1. import json
  2. json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
  3. from io import StringIO
  4. io = StringIO('["streaming API"]')
  5. json.load(io) # ['streaming API']
  6. from io import StringIO
  7. io = StringIO('[1,2,3]')
  8. json.load(io) # [1, 2, 3]

 

 

 



所属网站分类: 技术文章 > 博客

作者:小胖子

链接:https://www.pythonheidong.com/blog/article/170254/7277556ec56c3709b874/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

5 0
收藏该文
已收藏

评论内容:(最多支持255个字符)