Reputation: 1053
I am trying to pull specific IDs from a JSON file using Python (2.7). Here is what my JSON data looks like:
[{
"user_id": "78900",
"instance": "441",
"comment": "hello"
}, {
"user_id": "67732",
"instance": "442",
"comment": ""
}, {
"user_id": "55667",
"instance": "443",
"comment": ""
}, {
"user_id": "67890",
"instance": "444",
"comment": ""
}, {
"user_id": "59093899",
"instance": "445",
"comment": ""
}]
My goal is to pull all of the numbers for the "user_ids" only and put those into an array. I am still new to Python but I have ran a loop before in order to pull numbers from a txt file that only contained numbers. That looked something like this:
list = []
qa_ids = open("numbers.txt")
for line in qa_ids.readlines():
list.extend(line.split())
qa_ids.close()
However, I am thinking that I would need to do something different because:
I am only pulling numbers from JSON data which contains other text
I am pulling from JSON data instead of text
Any help would be greatly appreciated.
Thanks!
Upvotes: 0
Views: 651
Reputation: 11906
1) Load the file and parse the json:
json_data = json.load(open("filename.json"))
2) Use list comprehension to get all the user ids.
user_id_list = [x.get("user_id") for x in json_data]
Upvotes: 1