【问题标题】:How can I use this string to read dictionaries in Python?如何使用此字符串在 Python 中读取字典?
【发布时间】:2016-07-02 23:55:25
【问题描述】:

我有这个字符串。如何读出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"}]}'

【问题讨论】:

标签: python string ip


【解决方案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']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多