看来您的输入使用反斜杠作为转义字符,您应该先取消转义文本,然后再将其传递给json
:
>>> foobar = '{\\"body\\": \\"\\\\u05e9\\"}'
>>> import re
>>> json_text = re.sub(r'\\(.)', r'\1', foobar) # unescape
>>> import json
>>> print(json.loads(json_text)['body'])
?
不要'unicode-escape'
在JSON文本上使用编码;它可能会产生不同的结果:
>>> import json
>>> json_text = '["\\ud83d\\ude02"]'
>>> json.loads(json_text)
['
解决方法
在Bash CLI的Kubuntu 15.10上解析HTML响应以使用 Python 3.4
提取数据时,使用来print()
获取如下所示的输出:
\u05ea\u05d4 \u05e0\u05e9\u05de\u05e2 \u05de\u05e6\u05d5\u05d9\u05df
如何在应用程序中输出实际文本本身?
这是生成字符串的代码:
response = requests.get(url)
messages = json.loads( extract_json(response.text) )
for k,v in messages.items():
for message in v['foo']['bar']:
print("\nFoobar: %s" % (message['body'],))
这是从HTML页面返回JSON的函数:
def extract_json(input_):
"""
Get the JSON out of a webpage.
The line of interest looks like this:
foobar = ["{\"name\":\"dotan\",\"age\":38}"]
"""
for line in input_.split('\n'):
if 'foobar' in line:
return line[line.find('"')+1:-2].replace(r'\"',r'"')
return None
在搜寻该问题时,我发现了很多与Python
2有关的信息,但是
Python 3*
完全改变了Python中处理字符串,尤其是Unicode的方式。 *
如何 在Python 3中将示例字符串(\u05ea
)转换为字符(?
)?
附录:
以下是一些有关的信息message['body']
:
print(type(message['body']))
# Prints: <class 'str'>
print(message['body'])
# Prints: \u05ea\u05d4 \u05e0\u05e9\u05de\u05e2 \u05de\u05e6\u05d5\u05d9\u05df
print(repr(message['body']))
# Prints: '\\u05ea\u05d4 \\u05e0\\u05e9\\u05de\\u05e2 \\u05de\\u05e6\\u05d5\\u05d9\\u05df'
print(message['body'].encode().decode())
# Prints: \u05ea\u05d4 \u05e0\u05e9\u05de\u05e2 \u05de\u05e6\u05d5\u05d9\u05df
print(message['body'].encode().decode('unicode-escape'))
# Prints: ?? ???? ?????
\u05ea\u05d4 \u05e0\u05e9\u05de\u05e2 \u05de\u05e6\u05d5\u05d9\u05df
response = requests.get(url)
messages = json.loads( extract_json(response.text) )
for k,v in messages.items():
for message in v['foo']['bar']:
print("\nFoobar: %s" % (message['body'],))
def extract_json(input_):
"""
Get the JSON out of a webpage.
The line of interest looks like this:
foobar = ["{\"name\":\"dotan\",\"age\":38}"]
"""
for line in input_.split('\n'):
if 'foobar' in line:
return line[line.find('"')+1:-2].replace(r'\"',r'"')
return None
print(type(message['body']))
# Prints: <class 'str'>
print(message['body'])
# Prints: \u05ea\u05d4 \u05e0\u05e9\u05de\u05e2 \u05de\u05e6\u05d5\u05d9\u05df
print(repr(message['body']))
# Prints: '\\u05ea\u05d4 \\u05e0\\u05e9\\u05de\\u05e2 \\u05de\\u05e6\\u05d5\\u05d9\\u05df'
print(message['body'].encode().decode())
# Prints: \u05ea\u05d4 \u05e0\u05e9\u05de\u05e2 \u05de\u05e6\u05d5\u05d9\u05df
print(message['body'].encode().decode('unicode-escape'))
# Prints: ?? ???? ?????
在Bash CLI的Kubuntu 15.10上解析HTML响应以使用 Python 3.4
提取数据时,使用来print()
获取如下所示的输出:
如何在应用程序中输出实际文本本身?
这是生成字符串的代码:
这是从HTML页面返回JSON的函数:
在搜寻该问题时,我发现了很多与Python
2有关的信息,但是
Python 3*
完全改变了Python中处理字符串,尤其是Unicode的方式。 *
如何 在Python 3中将示例字符串(\u05ea
)转换为字符(?
)?
附录:
以下是一些有关的信息message['body']
: