python字符串怎么转换成字典_用python将字符串转换成字典

I know that this question sound a duplicate, but it's not, at least looked for a while and I couldn't fine nothing for my specific problem.

I have the following string:

"{first : {name : 'test', value : 100}, second : {name : 'test2', value : 50}}"

And I want to convert that string to a dictionary something like this:

{'first': {'name': 'test', 'value' : 100}, 'second': {'name': 'test2', 'value' : 50}}

Any ideas? I'm working with Python 2.5

Thanks

解决方案

First, if you're generating these strings from dictionaries (in Python or almost any other language), you might want to consider generating them in a way that can be easily parse. For example, in Python. either repr(d) or json.dumps(d) will give you something very similar to your existing string, but with proper quotes.

But if you've just got a mess of strings someone else gave you, the easiest thing to do might be to regex it into an actual JSON string so you can parse it:

json.loads(re.sub(r",\s*(\w+)", r", '\1'",

re.sub(r"\s*\{\s*(\w+)", r"{'\1'", x)).replace("'", '"'))

In 2.5, there's no built-in json module, so you probably want to pip install simplejson and then you can do this:

try:

import json

except ImportError:

import simplejson as json

(Or, of course, you can just require simplejson unconditionally, if you prefer.)

A different alternative is to use ast.literal_eval instead of json.loads. Which one is appropriate depends on more information about your strings. JSON is more restricted than Python syntax, so it's safer if you're worried about the source of your input, but not as flexible if your input might legitimately have stuff that JSON can't handle, like 1+3j.

However, like json, ast is new to 2.6, and there's no drop-in replacement available on PyPI. Fortunately, 2.5 does have the _ast module, and you can just copy and paste the source literal_eval from 2.6's ast.py, but this is a bit of a hassle. There are also recipes at ActiveState, such as http://code.activestate.com/recipes/364469/ that, while not identical to literal_eval, may be right for your purposes.

This still won't quite work, because you're also missing the closing right brace in the example string. I'm hoping that's a typo, in which case there's not a problem.

If not, you need to explain what you want it to actually do with such cases. Maybe auto-close any unclosed braces? If so, could unclosed brackets also be a problem?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值