|
楼主 |
发表于 2014-10-27 15:49
|
显示全部楼层
本帖最后由 wcymiss 于 2014-10-27 16:51 编辑
编写JavaScript代码处理JSON(一)
个人为了练习分析JavaScript、JSON的能力,常编写JavaScript处理JSON成一个“表格文本”,放入剪贴板后粘贴到工作表内。
此法需要学习JavaScript知识。http://www.w3school.com.cn/js/index.asp
仍以之前的JSON数据为例:- Sub Test()
- Const strJSON As String = "[{""name"":""甲"",""age"":36,""children"":[{""name"":""甲儿"",""age"":10},{""name"":""甲女"",""age"":7}]},{""name"":""乙"",""age"":28,""children"":[{""name"":""乙女"",""age"":6}]}]"
- Dim strJS As String
- Dim strTable As String
-
- '为了编写方便,假设每个Person的children数组里至少有一个元素:
- strJS = "var mydata=" & strJSON _
- & ";var i,j;var s='name\tage\tchildname\tchildage\r';" _
- & "for(i=0;i<mydata.length;i++){for(j=0;j<mydata[i].children.length;j++)" _
- & "{s+=mydata[i].name+'\t'+mydata[i].age+'\t'+mydata[i].children[j].name+'\t'+mydata[i].children[j].age+'\r'}};"
- strTable = JSEval(strJS)
- Debug.Print strTable
-
- CopyToClipbox strTable
- Cells.Clear
- Range("a1").Select
- ActiveSheet.Paste
- End Sub
- Function JSEval(strJS As String) As String
- With CreateObject("MSScriptControl.ScriptControl")
- .Language = "javascript"
- JSEval = .Eval(strJS)
- End With
- End Function
- Sub CopyToClipbox(strText As String)
- With CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
- .SetText strText
- .PutInClipboard
- End With
- End Sub
复制代码 JavaScript的'\t'相当于 vbTab,'\r'相当于 vbCr,取出值后,每列之间用'\t'连接,每行之间用'\r'连接,这样的文本复制到剪贴板后,可直接粘贴到工作表形成表格数据。
本法非主流,不喜勿用! |
评分
-
1
查看全部评分
-
|