Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

Here is my sample string:

[true, {"name": "NameofItem", "amount": "1", "price": 100, "sellerName": "Sellername1", "sellerId": 1},

{"name": "NameofItem2", "amount": "1", "price": 101, "sellerName": "Sellername2", "sellerId": 2}, 22250]

I need to find a way of grabbing the first instance of "price" and it's affiliated integer. I thought I could use re.match and

(\{.*?\}) to get a first set of content and then convert to a dictionary, but I can't seem to make that work.

1 Answer

0 votes
by (36.8k points)

Don't use a regex to parse well-formed JSON like this. Use the builtin json.loads function to parse the JSON string into an in-memory list data structure. Then you can access the first element in the list with L[1] and the "price" key in that dictionary with L[1]["price"]:

>>> s = '[true,{"name":"NameofItem","amount":"1","price":100,"sellerName":"Sellername1", "sellerId":1},{"name":"NameofItem2","amount":"1","price":101,"sellerName":"Sellername2","sellerId":2},22250]'

>>> import json

>>> L = json.loads(s)

>>> L

[True, {'name': 'NameofItem', 'amount': '1', 'price': 100, 'sellerName': 'Sellername1', 'sellerId': 1}, {'name': 'NameofItem2', 'amount': '1', 'price': 101, 'sellerName': 'Sellername2', 'sellerId': 2}, 22250]

>>> L[1]["price"]

100

>>> type(L[1]["price"])

<class 'int'>

Learn Python for Data Science Course to improve your technical knowledge. 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...