从字符串中提取预格式化的数据

2024-03-28 19:25:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过Python中的API接收以下字符串:

{"id":13021,"buys":{"quantity":3494,"unit_price":257},"sells":{"quantity":3187,"unit_price":433}}

我可以通过.find可靠地隔离"id"字段,但是"buys""sells""unit_price"项很难恢复,因为它们不共享唯一标识符。我的最佳选择是用正则表达式解析整个过程,还是Python提供了一个更直接的解决方案来访问所需的子字符串?你知道吗


Tags: 字符串apiid过程unit标识符find解决方案
2条回答
>>> from ast import literal_eval
>>> a = instr = '{"id":13021,"buys":{"quantity":3494,"unit_price":257},"sells":{"quantity":3187,"unit_price":433}}'
>>> b=literal_eval(a)
>>> b['sells']
{'unit_price': 433, 'quantity': 3187}
>>> 

您的输入数据是JSON。在这种情况下使用regexp是过分的。你可以把它转换成dict,然后像这样处理它

import json
instr = '{"id":13021,"buys":{"quantity":3494,"unit_price":257},"sells":{"quantity":3187,"unit_price":433}}'

injs = json.loads(instr)

injs["buys"]
Out[62]: {'quantity': 3494, 'unit_price': 257}

相关问题 更多 >