从API调用中提取数据并保存文件

时间:2019-11-11 08:44:30

标签: python json parsing for-loop extract

在调用API后,我要提取特定的键/值,然后将其保存到文本文件中。

到目前为止已经做了什么: (1)Rest api调用和返回列表

import requests
import json

#API details
url = "http://192.168.1.100:9792/api/scan"
body = json.dumps({"service":"scan", "user_id":"1", "action":"read_all", "code":"0"})
headers = {'Content-Type': 'application/json'}

#Making http post request
response = requests.post(url, headers=headers, data=body, verify=False)

#Decode response.json() method to a python dictionary for data process utilization
dictData = response.json()

#Json string
json_str = json.dumps(dictData)
print(json_str)

print(json_str)输出如下

{
  "node": [
    {
      "id": "123",
      "ip": "10.101.10.1",
      "model": "md1",
      "type": "basic",
      "name": "aaa"
    },
    {
      "id": "456",
      "ip": "10.101.10.2",
      "model": "sp3",
      "type": "extra",
      "name": "bbb"
    },
    {
      "id": "789",
      "ip": "1.1.1.1",
      "model": "md1",
      "type": "basic",
      "name": "ccc"
    },
    {
      "id": "101",
      "ip": "2.2.2.2",
      "model": "advance",
      "type": "sw1",
      "name": "ddd"
    }
  ],
  "status": "success"
}

(2)提取特定的键/值,这是我从列表中获取键/值时出错的地方

for i in json_str["node"]:
   if i["type"]=="basic" or i["type"]=="sw1" :
      print(i["name"],i["ip"], i["type"])

我遇到错误

for i in json_str["node"]:
TypeError: string indices must be integers, not str

我尝试更改为json_str [0],但它仍未返回我想要的键/值。 请进一步协助。谢谢

只需使用字典数据中已有的dictData

for i in dictData["node"]

1 个答案:

答案 0 :(得分:1)

您将json转储到str

要再次使用dict,请先加载json,然后再尝试

json_str = json.dumps(dictData)
json_dict = json.loads(json_str)
print(json_dict)