从.responseText提取特定的JSON字段到单个Excel单元格

时间:2018-10-18 02:20:41

标签: json excel vba api web-scraping

我正在尝试从JSON检索特定字段,以进行解析。我不确定如何才能获得这一领域。我添加了Msgbox [Exists&Fail],以查看代码是否能够读取单元格中的resolve字,但是返回失败。

有什么办法我只能让现场解决吗?请协助。

谢谢!

 TargetURL = "https://api.passivetotal.org/v2/dns/passive?query=passivetotal.org"
    actionType = "Content-Type"
    actionWord = "application/json"
    With CreateObject("Microsoft.XMLHTTP")
        .Open "GET", TargetURL, False
        .setRequestHeader actionType, actionWord
        .setRequestHeader "Authorization", "Basic <Encoded 64>"
        .send
        If .Status = 200 Then
            Sheets(6).Cells(Count, 10).Value = "Connected"
            Debug.Print .responseText
            MsgBox .responseText
            Set JSON = ParseJson(.responseText)
            Sheets(6).Cells(Count, 8).Value = .responseText
            If Sheets(6).Cells(Count, 8).Value = ("resolve") Then
                MsgBox ("Exists")
            Else
                MsgBox ("Fail")
            End If
        Else
            MsgBox .Status & ": " & .StatusText
        End If
    End With

1 个答案:

答案 0 :(得分:1)

解析JSON响应:

以下内容从文件中读取结果json并解析出每个解析。它使用JSONConverter.bas。请注意,我已经在我的python脚本中提取了“结果” JSON集合,这与您通过json("results")对转换后的JSON字符串进行Set json = JsonConverter.ParseJson(.responseText)("results")一样。

在您的项目中添加JSONConverter.bas后,您需要进入工具>参考>添加对Microsoft Scripting Runtime的参考

Option Explicit
Public Sub GetJSONExtract()
    Dim fso As Object, jsonFile As Object, jsonText As String, json As Object, item As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set jsonFile = fso.OpenTextFile("C:\Users\User\Desktop\Sample.json")
    jsonText = jsonFile.ReadAll
    Set json = JsonConverter.ParseJson(jsonText)  '<== Using results collection
    'Set json = JsonConverter.ParseJson(.responseText)("results")  '<== In your vba XMLHTTP version
    For Each item In json
        Debug.Print item("resolve")
    Next
End Sub

就像您在解析我所显示的JSON一样。


其他说明:

我实际上使用了下面显示的python脚本;改编自API文档。然后,我添加了一些代码,将响应写到JSON文件中,以便以后导入。使用Anaconda / Spyder运行。

import requests
import json

username = 'xxx'
key = 'yyy'
auth = (username, key)
base_url = 'https://api.passivetotal.org'

def passivetotal_get(path, query):
    url = base_url + path
    data = {'query': query}
    response = requests.get(url, auth=auth, json=data)
    return response.json()

pdns_results = passivetotal_get('/v2/dns/passive', 'passivetotal.org')

for resolve in pdns_results['results']:
   print('Found resolution: {}'.format(resolve['resolve']))


with open(r"C:\Users\User\Desktop\Output.json", "w") as text_file:
    text_file.write(json.dumps(pdns_results['results']))

这将打印出所有解析。

原始返回的JSON结构如下:

structure

返回的对象是词典的集合。您可以通过字典键"resolve"

访问所需的值