2

I come to python from js. I have list like:

[{_id: '1', data: {}}, {_id: '2', data: {}}] 

my goal is to get list of _id's like [1, 2]

3
  • 1
    Google Python list comprehension Commented Aug 9, 2020 at 9:47
  • 3
    Does this answer your question? How to get data from a list Json with python? Commented Aug 9, 2020 at 9:47
  • 1
    Yes, it is what I need Commented Aug 9, 2020 at 9:49

2 Answers 2

4

As it's javascript object, not a json, you need 3rd party library like demjson to convert it to json.

In [70]: import demjson

In [71]: demjson.decode("[{_id: '1', data: {}}, {_id: '2', data: {}}]")
Out[71]: [{'_id': '1', 'data': {}}, {'_id': '2', 'data': {}}]

In [72]: converted_json = demjson.decode("[{_id: '1', data: {}}, {_id: '2', data: {}}]")

In [74]: [int(i["_id"]) for i in converted_json]
Out[74]: [1, 2]
Sign up to request clarification or add additional context in comments.

Comments

2

Try this simple list comprehension -

j = [{'_id': '1', 'data': {}}, {'_id': '2', 'data': {}}]

#One liner
[int(i.get('_id')) for i in j]
[1,2]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.