我在 VBA 中使用 Deepl 的翻譯 API。我的請求作業得很好,并回傳了一些翻譯后的 html 文本。但是,我無法在回傳的物件中獲取“文本”值:
所以我的請求如下所示:
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
url = api & "?" & authKey & "&" & targetLng & "&" & tagHandling & "&" & sourceLng
Debug.Print url
objHTTP.Open "POST", url, False
objHTTP.setRequestHeader "Host", "api-free.deepl.com"
objHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Accept", "*/*"
objHTTP.send "text=" & text
textResponse = objHTTP.responseText 'textResponse is defined as String
Debug.Print textResponse
我得到以下輸出:
{
"translations":
[
{"detected_source_language":"DE",
"text":"<h2>SizeI</h2>love \"Paperwhite\".<br><br><img
src=\"https://ws-eu.amazon-adsystem.com/widgets/q?_encoding=UTF8"
}
]
}
我進一步嘗試:
'get the script control:
Set ScriptEngine = CreateObject("ScriptControl")
ScriptEngine.Language = "JScript"
'Get the string and parse it:
Set jsonObject = ScriptEngine.Eval("(" & textResponse & ")")
jsonObject 回傳[object Object],我不知道如何處理它。如何訪問此物件并僅回傳文本值?
uj5u.com熱心網友回復:
從這里使用 VBA-JSON:https ://github.com/VBA-tools/VBA-JSON
Function Test20220318()
Dim json As Object, txt, trans As Collection, t As Object, k
txt = [E1].Value 'using json stored in a cell for testing
Set json = JsonConverter.ParseJson(txt) 'a Dictionary object
Set trans = json("translations") 'access dictionary by key to get collection/array
For Each t In trans 'loop over items in collection/array
For Each k In t 'loop over keys in t
Debug.Print k, "=", t(k) 'print key and associated value
Next
Next t
End Function
uj5u.com熱心網友回復:
回應是一個 JSON 字串。您必須將 JSON 字串轉換為物件
Set jsonObject = DecodeJsonString(objHTTP.responseText)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/447647.html
下一篇:C 中物件和變數的區別
