json.loads不会保留双引号完整 [英] json.loads does not keep double quotes intact

查看:358
本文介绍了json.loads不会保留双引号完整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用json.loads时,它将双引号转换为单引号. 这让我感到困扰,有人可以帮忙澄清一下吗?

When I use json.loads, it converts double quotes into single quotes. This is troubling me, can someone help in clarifying this?

>>> import simplesjson as json
>>> string = '{"created_at": "2012/02/05 04:03:50 -0800"}'
>>> json.loads(string,'utf-8')
{'created_at': '2012/02/05 04:03:50 -0800'}

我知道这是正常现象,我可以轻松调整代码.但是,思考是否可以实现相同的目标?

I understand that this is a normal behavior and i can tweak my code easily. But thinking whether same can be achieved or not?

推荐答案

首先:引号不是值的一部分.它们是语法的一部分,向解析器表示已定义了字符串.

First of all: quotes are not part of the value. They are part of the syntax, signalling to the parser that a string is defined.

JSON仅支持双引号,但是在 Python 中,可以使用单引号或双引号定义字符串.当回显字符串值时,Python通过向您显示Python语法以重新定义相同的值来反映该值.对于此表示形式,单引号是首选.仅当该值实际包含至少一个单引号并且不包含双引号时,才会使用双引号:

JSON only supports double quotes, but in Python, strings can be defined using either single or double quotes. When echoing a string value, Python reflects the value by showing you Python syntax to redefine the same value. For this representation single quotes are preferred. Only if the value actually contains at least one single quote and no double quotes would double quotes be used:

>>> "Normal strings are reflected with single quotes by Python"
'Normal strings are reflected with single quotes by Python'
>>> 'Single quote: \''
"Single quote: '"
>>> 'Single quote: \', and a double quote: \"'
'Single quote: \', and a double quote: "'

您看到的是完全正常的行为.您无法更改此设置;您看到的输出是调试工具.如果需要更改,请制作自己的格式化程序.

What is you see is entirely normal behaviour. You can't change this; the output you see is a debugging tool. Produce your own formatter if this is something you want to change.

当您再次从Python结构中生成JSON时,将仅使用双引号来生成有效的JSON输出:

When you produce JSON from the Python structure again, only double quotes will be used to produce valid JSON output:

>>> import json
>>> json_string = '{"created_at": "2012/02/05 04:03:50 -0800"}'
>>> json.loads(json_string)
{u'created_at': u'2012/02/05 04:03:50 -0800'}
>>> json.dumps(json.loads(json_string))
'{"created_at": "2012/02/05 04:03:50 -0800"}'

这篇关于json.loads不会保留双引号完整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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