我正在使用Python 2从ASCII编码的文本文件中解析JSON .
使用json或 加载这些文件时simplejson,我的所有字符串值都转换为Unicode对象而不是字符串对象.问题是,我必须使用一些只接受字符串对象的库的数据.我不能更改库也不能更新它们.
是否可以获取字符串对象而不是Unicode对象?
>>> import json
>>> original_list = ['a', 'b']
>>> json_list = json.dumps(original_list)
>>> json_list
'["a", "b"]'
>>> new_list = json.loads(json_list)
>>> new_list
[u'a', u'b'] # I want these to be of type `str`, not `unicode`Run Code Online (Sandbox Code Playgroud)
很久以前,当我遇到Python 2时,问了这个问题.今天一个简单而干净的解决方案是使用最新版本的Python - 即Python 3和转发版.
如何解析/读取YAML文件到Python对象?
例如,这个YAML:
Person:
name: XYZ
Run Code Online (Sandbox Code Playgroud)
对于这个Python类:
class Person(yaml.YAMLObject):
yaml_tag = 'Person'
def __init__(self, name):
self.name = name
Run Code Online (Sandbox Code Playgroud)
我顺便使用PyYAML.
json.dumps 使用科学记数法输出小的浮点数或十进制值,这对于将此输出发送到的 json-rpc 应用程序是不可接受的。
>>> import json
>>> json.dumps({"x": 0.0000001})
'{"x": 1e-07}'
Run Code Online (Sandbox Code Playgroud)
我想要这个输出:
'{"x": 0.0000001}'
Run Code Online (Sandbox Code Playgroud)
最好避免引入额外的依赖项。