Kibbles
Kibbles

Reputation: 75

Extract pre-formatted data from a String

I am receiving the following string via an API in Python:

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

I can reliably isolate the "id" field via .find, but the "buys" and "sells" entries for "unit_price" are harder to recover since they don't share unique identifiers. Is my best bet to parse the whole thing with regular expressions, or does Python offer a more straightforward solution to access the required substrings?

Upvotes: 0

Views: 81

Answers (2)

kvorobiev
kvorobiev

Reputation: 5070

Your input data is JSON. Using regexp in this case is overkill. You could convert it to dict and work with it like

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}

Upvotes: 1

dsgdfg
dsgdfg

Reputation: 1510

>>> 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}
>>> 

Upvotes: 1

Related Questions