使用python json.loads解析unicode输入 [英] Parsing unicode input using python json.loads

查看:696
本文介绍了使用python json.loads解析unicode输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中加载JSON字符串的最佳方法是什么?



我想使用json.loads来处理unicode,如下所示:

 导入json 
json.loads(unicode_string_to_load)

我还尝试提供值为'utf-16'的'encoding'参数,但错误并没有消失。



完整的SSCCE具有错误:

 #-*-编码:utf-8-*-
import json
value = '{ foo: bar}'
print(json.loads(value)['foo'])#这是正确的,打印'bar'

some_unicode = unicode( degradé)
#最后一个字符是带有尖锐 \xe3\xa9的拉丁字母e
value ='{ foo:'+ some_unicode +'}''
打印(json.loads(value)['foo'])#错误,抛出错误

错误:

  UnicodeDecodeError:'ascii'编解码器无法解码
位置的字节0xc3 6:序数不在范围内(128)


解决方案

我使用'latin-1'将字符串转换为unicode字符串,从而修复了错误:

  UnicodeDecodeError:'utf16 '编解码器无法在
位置6解码字节0x38:截断的数据

固定代码:

  import json 

ustr_to_load = unicode(str_to_load,'latin-1')

json.loads(ustr_to_load)

然后不会引发错误。


What is the best way to load JSON Strings in Python?

I want to use json.loads to process unicode like this:

import json
json.loads(unicode_string_to_load)

I also tried supplying 'encoding' parameter with value 'utf-16', but the error did not go away.

Full SSCCE with error:

# -*- coding: utf-8 -*-
import json
value = '{"foo" : "bar"}'
print(json.loads(value)['foo'])     #This is correct, prints 'bar'

some_unicode = unicode("degradé")  
#last character is latin e with acute "\xe3\xa9"
value = '{"foo" : "' + some_unicode + '"}'
print(json.loads(value)['foo'])            #incorrect, throws error

Error:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 
6: ordinal not in range(128)

解决方案

I typecasting the string into unicode string using 'latin-1' fixed the error:

UnicodeDecodeError: 'utf16' codec can't decode byte 0x38 in 
position 6: truncated data

Fixed code:

import json

ustr_to_load = unicode(str_to_load, 'latin-1')

json.loads(ustr_to_load)

And then the error is not thrown.

这篇关于使用python json.loads解析unicode输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆