json - 使用 VBA 写入部分数据
问题描述
我有一个很大的 JSON 文件,但我需要的信息只是其中的一小部分。有什么方法可以提取我想要的部分并写入 Excel 工作表而不是写入整个文件?请看下面的例子。我只想提取“文本”部分
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
}
解决方案
如果它是一个 JSON 文件,您可以阅读如下内容并将其清空到工作表中
Option Explicit
Public Sub GetInfo()
Dim strJSON As String, json As Object, rowNumber As Long
Application.ScreenUpdating = False
Const PATH As String = "C:\Users\User\Desktop\test.JSON"
strJSON = GetJSONFromFile(PATH)
Set json = JsonConverter.ParseJson(strJSON)
Set json = json("widget")("text")
Dim key As Variant
With ThisWorkbook.Worksheets("Sheet1")
For Each key In json
rowNumber = rowNumber + 1
.Cells(rowNumber, 1) = key
.Cells(rowNumber, 2) = json(key)
Next key
End With
Application.ScreenUpdating = True
End Sub
Public Function GetJSONFromFile(ByVal PATH As String) As String
Dim fso As Object, f As Object, outputString As String
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(PATH)
Do Until f.AtEndOfStream
outputString = f.ReadAll()
Loop
f.Close
GetJSONFromFile = outputString
End Function
如果您检查 JSON,您可以看到顶级字典有一个"widget"
可以访问内部字典的键。其中之一有钥匙"text"
;那是您所追求的,可以使用语法访问
Set json = json("widget")("text")
您可以将顶部的子代码缩短为:
Option Explicit
Public Sub GetInfo()
Dim strJSON As String, json As Object, rowNumber As Long
Application.ScreenUpdating = False
Const PATH As String = "C:\Users\HarrisQ\Desktop\test.JSON"
strJSON = GetJSONFromFile(PATH)
Set json = JsonConverter.ParseJson(strJSON)
Set json = json("widget")("text")
With ThisWorkbook.Worksheets("Sheet1")
.Cells(1, 1).Resize(json.Count) = Application.WorksheetFunction.Transpose(json.keys)
.Cells(1, 2).Resize(json.Count) = Application.WorksheetFunction.Transpose(json.Items)
End With
Application.ScreenUpdating = True
End Sub
推荐阅读
- javascript - 如何使用扩展语法将新元素推送到 JavaScript 中的嵌套对象数组
- permissions - Rsync 未在目标目录上设置 SGID 位
- django - 如何在 django 的管理面板中存储用户提出的投诉
- java - 有没有一种方法可以让我无需在 android 中打开网站就可以在点击按钮时访问 url?
- javascript - 无法更改antd V4选择后缀图标,同时打开选项列表
- html - Django 模板:块标签
- git - 如何忽略git中的文件
- java - 为什么我在存储库上收到错误“未找到属性”?
- nginx - Next js 和 google 分析在 nginx 反向代理后面不起作用
- javascript - Bootstrap-vue 导航栏未按预期呈现