我想知道最简单的方法是将string如下列表转换为list:
x = u'[ "A","B","C" , " D"]'
即使用户在逗号和引号内的空格之间放置空格也是如此.我需要处理它:
x = ["A", "B", "C", "D"] 
在Python中.
我知道我可以剥夺的空间与strip()和split()使用拆分操作和检查非字母.但是代码变得非常糟糕.有一个我不知道的快速功能吗?
我将收到一个JSON编码的字符串形式Obj-C,我正在解码一个虚拟字符串(现在),如下面的代码.我的输出带有每个项目前缀字符'u':
[{u'i': u'imap.gmail.com', u'p': u'aaaa'}, {u'i': u'333imap.com', u'p': u'bbbb'}...
JSON如何添加这个unicode char?删除它的最佳方法是什么?
mail_accounts = []
da = {}
try:
    s = '[{"i":"imap.gmail.com","p":"aaaa"},{"i":"imap.aol.com","p":"bbbb"},{"i":"333imap.com","p":"ccccc"},{"i":"444ap.gmail.com","p":"ddddd"},{"i":"555imap.gmail.com","p":"eee"}]'
    jdata = json.loads(s)
    for d in jdata:
        for key, value in d.iteritems():
            if key not in da:
                da[key] = value
            else:
                da = {}
                da[key] = value
        mail_accounts.append(da)
except Exception, err:
    sys.stderr.write('Exception Error: %s' % str(err))
print mail_accounts
当我使用YAML加载带有e形式的JSON转储的数字时,该数字将作为字符串而不是浮点数加载.
我想这个简单的例子可以解释我的问题.
import json
import yaml
In [1]: import json
In [2]: import yaml
In [3]: All = {'one':1,'low':0.000001}
In [4]: jAll = json.dumps(All)
In [5]: yAll = yaml.safe_load(jAll)
In [6]: yAll
Out[6]: {'low': '1e-06', 'one': 1}
YAML将1e-06加载为字符串而不是数字?我该如何解决?
我做了一个小测试用例来比较YAML和JSON的速度:
import json
import yaml
from datetime import datetime
from random import randint
NB_ROW=1024
print 'Does yaml is using libyaml ? ',yaml.__with_libyaml__ and 'yes' or 'no'
dummy_data = [ { 'dummy_key_A_%s' % i: i, 'dummy_key_B_%s' % i: i } for i in xrange(NB_ROW) ]
with open('perf_json_yaml.yaml','w') as fh:
    t1 = datetime.now()
    yaml.safe_dump(dummy_data, fh, encoding='utf-8', default_flow_style=False)
    t2 = datetime.now()
    dty = (t2 - t1).total_seconds()
    print 'Dumping %s row into a yaml file : %s' % (NB_ROW,dty)
with open('perf_json_yaml.json','w') as fh:
    t1 …我正在使用json.dump()和json.load()来保存/读取磁盘的字符串字典.问题是我不能在unicode中使用任何字符串.无论我如何将参数设置为dump/load(包括ensure_ascii和encoding),它们似乎都是unicode.
我有一个这样的.json文件(命名为meta.json):
{
    "main": {
        "title": "????????",
        "description": "????????"
    }
}
我想将它转换为一个.yaml  文件(命名为meta.yaml),如:
title: "????????"
description: "????????"
我所做的是:
import simplejson as json
import pyyaml
f = open('meta.json', 'r')
jsonData = json.load(f)
f.close()
ff = open('meta.yaml', 'w+')
yamlData = {'title':'', 'description':''}
yamlData['title'] = jsonData['main']['title']
yamlData['description'] = jsonData['main']['description']
yaml.dump(yamlData, ff)
# So you can  see that what I need is the value of meta.json     
但遗憾的是,我得到的是:
{description: "\u4ECA\u65E5\u306F\u96E8\u304C\u964D\u3063\u3066", title: "\u4ECA\u65E5\
\u306F\u96E8\u304C\u964D\u3063"}
为什么?
作为从JSON API调用解析的多级字典,我有很多输入.字符串都是unicode,这意味着有很多u'stuff like this'.我正在使用jq来处理结果,需要将这些结果转换为ASCII.
我知道我可以编写一个函数来像这样转换它:
def convert(input):
    if isinstance(input, dict):
        ret = {}
        for stuff in input:
            ret = convert(stuff)
    elif isinstance(input, list):
        ret = []
        for i in range(len(input))
            ret = convert(input[i])
    elif isinstance(input, str):
        ret = input.encode('ascii')
    elif :
        ret = input
    return ret
这甚至是正确的吗?不确定.这不是我想问你的.
我要问的是,这是解决问题的典型蛮力解决方案.肯定有更好的办法.一种更加pythonic的方式.我不是算法专家,但这个也不是特别快.
那么还有更好的方法吗?或者如果没有,可以改进这个功能......?
回答后编辑
Mark Amery的回答是正确的,但我想发布它的修改版本.他的函数适用于Python 2.7+而我在2.6上,所以不得不转换它:
def convert(input):
    if isinstance(input, dict):
        return dict((convert(key), convert(value)) for key, value in input.iteritems())
    elif isinstance(input, list):
        return [convert(element) for element …我有一个JSON配置文件,包含一些变量作为字符串(总是ascii).默认情况下,这些字符串被解码为unicode,但由于我必须将这些变量传递给我的Python C Extensions,我需要它们作为普通的Python字符串.目前我正在使用str(unicode)转换JSON字符串,但是更加优雅且不那么详细的解决方案将非常受欢迎.
有没有办法使用自定义JSONDecoder或对象挂钩将默认转换从字符串更改为unicode ?
我得到了以下json:{u'a': u'aValue', u'b': u'bValue', u'c': u'cValue'}通过request.json我的python代码.现在,我想将unicode json转换为普通的json,这应该是这样的:{"a": "aValue", "b": "bValue", "c": "cValue"}.如何在不进行任何手动更换的情况下完成此操作?请帮忙.
考虑这个功能:
def escape(text):
    print repr(text)
    escaped_chars = []
    for c in text:
        try:
            c = c.decode('ascii')
        except UnicodeDecodeError:
            c = '&{};'.format(htmlentitydefs.codepoint2name[ord(c)])
        escaped_chars.append(c)
    return ''.join(escaped_chars)
它应该通过相应的htmlentitydefs转义所有非ascii字符.不幸的是python抛出
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 0: ordinal not in range(128)
当变量text包含字符串,其repr()是u'Tam\xe1s Horv\xe1th'.
但是,我不使用str.encode().我只用str.decode().我错过了什么吗?