Функция предназначена для перевода ответа веб-сервера в формате JSON в читаемый текст.
Пример использования функции JSON_decode:
Sub test_JSON_decode()
' исходная строка в кодировке JSON
txt$ = "<th class=\""label\"">\u0428\u0442\u0440\u0438\u0445\u043a\u043e\u0434<\/th>\n <td class=\""data\"">408<\/td>\n"
Debug.Print JSON_decode(txt)
' на выходе получаем: <th class="label">Штрихкод</th> <td class="data">408</td>
End Sub
Код функции JSON_decode:
Function JSON_decode(ByVal txt$) As String
On Error Resume Next
Static REGEXP As Object
If REGEXP Is Nothing Then Set REGEXP = CreateObject("VBScript.RegExp"): REGEXP.Global = True
REGEXP.pattern = "\\u[A-Fa-f0-9]{4}"
JSON_decode = txt$
Dim coll As New Collection, char$, item As Variant
If REGEXP.test(txt$) Then
Set objMatches = REGEXP.Execute(txt$) ' ищем в тексте коды символов вида \u034a
For Each m In objMatches
coll.Add m.Value, CStr(m.Value)
Next
End If
For Each item In coll ' преобразуем коды символов кириллицы в текст
char$ = ChrW(Val(Replace(item, "\u", "&h"))) ' например, из \u0410 в «А»
txt = Replace(txt, item, char$)
Next
For Each item In Array("""", "/") ' убираем слеш перед спецсиволами
txt = Replace(txt, "\" & item, item)
Next
txt = Replace(txt, "\n", vbNewLine) ' перевод строки
JSON_decode = txt$
End Function
- Добавить комментарий
- Задать вопрос разработчику на почту
- 11.074 просмотра