Trích xuất dữ liệu từ tệp JSON bằng Python [trùng lặp]
Nov 08 2020
Chào mọi người! Tôi cần lấy tất cả các tên trong "bộ phát trực tiếp", nhưng tôi thực sự không biết làm cách nào để làm được điều này. Có lẽ bạn có thể giúp tôi.
Cảm ơn!
Tệp JSON:
"streamers": [
{},
{
"name": "One\n\n"
},
{
"name": "Two\n\n"
},
{
"name": "Three\n\n"
}
]
}
Trả lời
jojo_Berlin Nov 08 2020 at 01:51
được rồi về cơ bản bạn có thể làm gì:
import json
names=[]
with open('data.txt') as json_file:
dict=json.load(json_file)["streamers"]
for tuple in dict:
if "name" in tuple:
names.append(tuple["name"]
print(names)
MelvinAbraham Nov 08 2020 at 01:49
Bạn có thể sử dụng loadphương pháp từ jsonmô-đun. Hàm này chấp nhận một trình xử lý tệp, đặc biệt là tệp JSON, sau đó nó chuyển đổi nó thành đối tượng từ điển Python mà bạn có thể sử dụng ngay trong mã của mình.
Bạn có thể tham khảo đoạn mã sau:
import json
f = open('path/to/file/file.json') # Open the JSON file
dictionary = json.load(f) # Parse the JSON file
f.close() # Close the JSON file
streamers = dictionary['streamers']
print(streamers)
Đầu ra
[
{},
{
"name": "One\n\n"
},
{
"name": "Two\n\n"
},
{
"name": "Three\n\n"
}
]
Gabip Nov 08 2020 at 02:00
Thử:
import json
with open('path/to/file.json') as f:
names = [x.get("name") for x in json.load(f)["streamers"] if x.get("name")]
print(names)