json - 如何正确将JSON导入Excel

标签 json excel vba

我的目标是搜索一些数据并将结果返回到 Excel 表格中。我正在使用 newsapi.org 服务并使用 VBA 来执行此操作。

我正在向 newsapi.org 发送 XMLHttpRequest 并成功接收 (JSON) 响应,我可以将其保存到桌面上的文件中。但是,我无法将该响应导入 Excel,因为我收到运行时错误 13:类型不匹配。

奇怪的是,当我将源更改为不同的 JSON 文件时,它起作用了。例如http://jsonplaceholder.typicode.com/users

所以我假设问题出在我收到的 JSON 响应的类型上。

Public Sub xmlhttptutorial()

Dim xmlhttp As Object
Dim myurl As String
Dim JSON As Object
Dim myFile As String
Dim i As Integer
Dim ws As Worksheet
Set xmlhttp = CreateObject("MSXML2.XMLHTTP")
Set ws = Sheet2
myFile = "C:\Users\A0781525\Desktop\myFile.txt"
myurl = "https://newsapi.org/v2/everything?q=Ashley%20Madison%20Data%20Breach&"
xmlhttp.Open "GET", myurl, False
xmlhttp.Send
Set JSON = JsonConverter.ParseJson(xmlhttp.ResponseText)
Open myFile For Output As #1: Print #1, xmlhttp.ResponseText: Close #1
i = 2
For Each Item In JSON
    Range("A2").Value = Item("articles")("0:")("source")("id:")
    Range("A2").Value = Item("articles")("0:")("source")("name")
    Range("A2").Value = Item("articles")("0:")("title")
i = i + 1
Next
End Sub

中断发生在以下行: Range("A2").Value = Item("articles")("0:")("source")("id:")

我收到的 JSON 文件输出示例:

{"status":"ok","totalResults":16,"articles":[{"source":{"id":"mashable","name":"Mashable"},"author": "Jack Morse","title":"色情网站泄露了超过一百万用户的私有(private)信息","description":"互联网的伟大之处在于没有人知道你对无尽色情内容有严重的兴趣。除非,也就是说,您拥有帐户的色情网站泄露了您的个人信息。超过一百万 Luscious.net 帐户持有者面临着这种意外…","url":"https://mashable.com/article/porn-site-leaks-users-data/ ","urlToImage":"https://mondrian.mashable.com/2019%252F08%252F20%252F24%252F62fc9aa277d54b2092a39393d2202a62.856fe.jpg%252F1200x630.jpg?signature=MBXieHs3n4uvowiVyV4K8cCO4j4= ","publishedAt":"2019-08-20T22:36:24Z","content":"互联网的伟大之处在于,没有人必须知道你对色情内容有严重的兴趣。除非,也就是说,您拥有帐户的色情网站泄露了您的个人信息。\r\n超过一百万 Luscious.net 帐户持有者遇到了 unex…[+2840 个字符]"}

最佳答案

您错误地解析了 JSON。可能是由于对其构造方式的误解。

尝试如下:

i = 2
'Cells.Clear
For Each item In JSON("articles")
    Cells(i, 1).Value = item("source")("id")
    Cells(i, 2).Value = item("source")("name")
    Cells(i, 3).Value = item("title")
i = i + 1
Next

关于json - 如何正确将JSON导入Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57606528/

相关文章:

javascript - 如何动态访问递增的json值

Python 请求正文自动添加单引号

javascript - 如何更新 nodejs 中的全部或大部分 JSON 值?

excel - 如何用已知值之间的线性级数填充空白列

vba - 在 VBA 中删除单元格值的一部分

javascript - 按日期键对 JSON 数组排序

Excel::Writer::XLSX 在公式中添加意外的 @

excel - ……:mm:ss format causing IF statement to return False

excel - 自动筛选错误 : the object invoked has disconnected from its clients

excel - VBA - 无法设置工作表变量