{"orders": [{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6}, {"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":648}, {"id":649},{"id":650},{"id":651},{"id":652},{"id":653} ] }
need to extract only numbers by using regex in python
I try to address the numbers but I can’t i just want the number in the list
Advertisement
Answer
A regex isn’t appropriate here, but you can get all the id
numbers with a simple list comprehension:
>>> d = {"orders":[{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":648},{"id":649},{"id":650},{"id":651},{"id":652},{"id":653}]} >>> [o["id"] for o in d["orders"]] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 648, 649, 650, 651, 652, 653]
If what you have is a string, luckily it’s valid JSON, so use json.loads
to turn it into a dictionary:
>>> j = '''{"orders": [{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6}, ... {"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":648}, ... {"id":649},{"id":650},{"id":651},{"id":652},{"id":653} ... ] ... }''' >>> import json >>> [o["id"] for o in json.loads(j)["orders"]] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 648, 649, 650, 651, 652, 653]