vba把json转数组中_在Excel VBA中解析JSON数组

这篇博客介绍了如何在Excel VBA中解析包含JSON数组的响应,并将数据横向填充到工作表的列A中。作者遇到的问题是理解ScriptControl对象的使用以及如何从API获取的JSON数据中提取特定值。最终解决方案通过修改代码,成功实现了从JSON的details数组中提取trade和trade_tenor信息,并打印到调试窗口。
摘要由CSDN通过智能技术生成

I have tried to follow the method in another thread, however there are certain part in the code that I don't understand and it didn't work for me. And I could comment as I haven't reached 50 reputations. (i included the response from the other thread)

I am trying to access to Json response as below, I would like to get the array after details into excel horizontally(column A1-A6), however in the other post, I don't understand what the script control method.

And there wasn't any comment line to explain what is it. And I tried to use it, the code just failed at sc.Eval "var obj=(" & json & ")"

Also, the line json = {get your json here} failed, instead i replaced that to Json = resp , where resp is the output returned from the API.

Your help is greatly appreciated.

Sub Tester()

Dim json As String

Dim sc As Object

Dim o

Set sc = CreateObject("scriptcontrol")

sc.Language = "JScript"

json = {get your json here}

sc.Eval "var obj=(" & json & ")" 'evaluate the json response

'add some accessor functions

sc.AddCode "function getSentenceCount(){return obj.sentences.length;}"

sc.AddCode "function getSentence(i){return obj.sentences[i];}"

Debug.Print sc.Run("getSentenceCount")

Set o = sc.Run("getSentence", 0)

Debug.Print o.trans, o.orig

End Sub

JSON response from API

{"details":[

{

"trade":"Micro",

"trade_tenor":"5yr+"

},

{

"trade":"Odd",

"trade_tenor":"10yr+"

},

{

"trade":"Round",

"trade_tenor":"20yr+"

} ]}

解决方案

Only needs some minor modifications:

Sub Tester()

Dim json As String

Dim sc As Object

Dim o, i, num

Set sc = CreateObject("scriptcontrol")

sc.Language = "JScript"

json = Range("A1").Value '{get your json here}

sc.Eval "var obj=(" & json & ")" 'evaluate the json response

'add some accessor functions

sc.AddCode "function getTradeCount(){return obj.details.length;}"

sc.AddCode "function getTrade(i){return obj.details[i];}"

num = sc.Run("getTradeCount")

For i = 0 To num - 1

Set o = sc.Run("getTrade", i)

Debug.Print o.trade, o.trade_tenor

Next i

End Sub

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值