JavaScript
x
6
1
{"orders": [{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},
2
{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":648},
3
{"id":649},{"id":650},{"id":651},{"id":652},{"id":653}
4
]
5
}
6
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:
JavaScript
1
4
1
>>> 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}]}
2
>>> [o["id"] for o in d["orders"]]
3
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 648, 649, 650, 651, 652, 653]
4
If what you have is a string, luckily it’s valid JSON, so use json.loads
to turn it into a dictionary:
JavaScript
1
9
1
>>> j = '''{"orders": [{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},
2
"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":648}, {
3
"id":649},{"id":650},{"id":651},{"id":652},{"id":653} {
4
]
5
''' }
6
>>> import json
7
>>> [o["id"] for o in json.loads(j)["orders"]]
8
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 648, 649, 650, 651, 652, 653]
9