如何使用此字符串在Python中读取字典?

时间:2016-03-16 21:06:33

标签: python string ip

我有这个字符串。我怎样才能读出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"}]}'

1 个答案:

答案 0 :(得分:1)

如果你想走这条路,你可以使用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']