[英]How can I use this string to read dictionaries in Python?
我有這個字符串。 如何讀取IP和FW數據?
new_string = b'{"data":[{"ip":"103.170.120.105","fw":"443"},
{"ip":"185.181.217.91","fw":"204"},
{"ip":"135.203.68.159","fw":"105"}]}'
您可以使用JSON模塊,也可以使用ast.literal_eval。
使用JSON,
import json
new_string = b'{"data":[{"ip":"103.170.120.105","fw":"443"},{"ip":"185.181.217.91","fw":"204"},{"ip":"135.203.68.159","fw":"105"}]}'
# If you're using Python3, you may need to do this:
new_string = new_string.decode('utf-8')
json_string = json.loads(new_string)
data = json_string['data']
for item in data:
# your ip and fw will be accessible
# as item['ip'] and item['fw']
print item['ip'], item['fw']
使用ast.literal_eval:
import ast
new_string = b'{"data":[{"ip":"103.170.120.105","fw":"443"},{"ip":"185.181.217.91","fw":"204"},{"ip":"135.203.68.159","fw":"105"}]}'
# If you're using Python3, you may need to do this:
new_string = new_string.decode('utf-8')
my_dictionary = ast.literal_eval(new_string)
data = my_dictionary['data']
for item in data:
# your ip and fw are accessible the same way as above
print item['ip'], item['fw']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.