python json转换与处理

http://blog.csdn.net/pipisorry/article/details/38662805

类型转换

python列表和json格式的相互转换

字符串和字典的互相转换

json.dumps:将dict转换成json格式的str

python3:

json.dumps(ner_result, ensure_ascii=False)

总是返回str(无编码的unicode)。

python2:

    a = json.dumps(dict1, ensure_ascii=False).encode('utf-8') #当输入是unicode或者loads结果时

    a = json.dumps(dict1, ensure_ascii=False) #当输入是utf-8时

参数:1 ensure_ascii    如果有中文需要ensure_ascii=False,表示输出编码不是ascii(这个意思只是说输出不是ascii编码,加上,encoding='utf-8'参数也只是对输入处理,但是输入如果是unicode,输出居然又被变成了unicode,也就是说ensure_ascii=False时,不管其它参数,输入是什么编码输出就是什么编码,输入是unicode,输出就是unicode,输入是utf-8,输出就是utf-8。If ``ensure_ascii`` is false, all non-ASCII characters are not escaped, and the return value may be a ``unicode`` instance.)

   2 encoding='utf-8'默认 是对输入的编码,没什么卵用。

Note:  1  dict1中的编码必须一致,都为utf-8编码或者都没有编码是unicode。所以再次使用json.dumps({'中文'.decode('utf-8'): json.load(...)})需要对齐编码。

    2 json.dumps(None) 返回 'null'字符串,而不是返回None。

json.loads:json格式的str转换成dict

python3:

    dict0 = json.loads(a, encoding='utf-8')

python2:

    dict0 = json.loads(a)

总返回unicode

        py2: Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object.    If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to ``unicode`` first. 即在py2中loads参数只能是str(默认utf-8编码的,其它编码必须使用参数encoding指定)或者是unicode。函数返回return cls(encoding=encoding, **kw).decode(s),所以loads总是返回的unicode.
        py3: Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python object. The ``encoding`` argument is ignored and deprecated. py3中貌似无所谓有无编码,因为py3中str就是unicode,bytes就是带编码的。函数返回return cls(**kw).decode(s),在py3中是str,即也是总返回unicode。

[Json概述以及python对json的相关操作(转)]
皮皮Blog

python读写json文件

json序列化比pickle[python模块 - pickle模块 ]更紧凑,而且最重要的是这样与JavaScript和许多其他语言兼容。然而对于复杂的对象,其中的一些信息可能丢失。

with open(json_file, encoding='utf-8) as in_file:   #打开文件时指定编码,可读取中文

    data = json.load(in_file)

    # data = json.loads(data)

问题解决:org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject

应用示例

配置文件搞成json格式,然后代码中直接读取

model_config_file = os.path.join(".", "model", "model_config.json")
with open(model_config_file, "r", encoding="utf-8") as f:
    model_config_dict = json.load(f)
model_config = ModelConfig(**model_config_dict)

from: python json转换与处理_-柚子皮-的博客-CSDN博客

ref: [json — JSON encoder and decoder]

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值