Output array to excel with VBA - json

Im am trying to output an array coming from JsonConverter to excel but I get an error 1004:
Sub test()
Dim parsed As Object
Dim myArray As Variant
Set parsed = JsonConverter.ParseJson("{""a"":123,""b"":[1,2,3,4],""c"":{""d"":456}}")
Set myArray = parsed("b")
Set TxtRng = ThisWorkbook.Sheets("Project").Range("A44:D44")
TxtRng.Value = Application.Transpose(myArray)
End Sub
The error is at TxtRng.Value = Application.Transpose(myArray).
Can someone help solve this issue? Thank you.

First: You shouldn't assume that it is commonly known what JsonConverter because it is not a build-in object. I assume you are talking about https://github.com/VBA-tools/VBA-JSON ?
In your example, parsed will return a Dictionary and parsed("b") will return a Collection. Application.Transpose expects a (2-dimensional) array as parameter, but will not work with a collection.
Probably the easiest way to solve this is simply to loop over the collection. Or use a helper function like similar to Converting VBA Collection to Array to create an intermediate array first

Related

JsonConverter Excel VBA multiple results

A small question: i'm using JsonConverter from Github.
(https://github.com/VBA-tools/VBA-JSON/blob/master/JsonConverter.bas)
Code is working on most of the "GET" request.
Only when the same 'column' is accuring multiple times in the 'ResponseText' then it's not. (like "imei" in the example)
So I need a way to handle a long 'Responsetext' to fill multiple rows in an access db.
Dim Json As Object
Set Json = JsonConverter.ParseJson(xmlhttp.ResponseText)
MsgBox (Json("imei")) 'temp
Error 5: Invalid Procedure or Call Argument.
Any ideas?
Many thanks,
I can only provide a part of the answer, because I cannot recreate it, without the full JSON Response Text:
The response with mutliple values in JSON returns an Object of the type Collection. Hence you have to use a loop to iterate through all responses. Like this:
Dim Json As Object
Set Json = JsonConverter.ParseJson(xmlhttp.ResponseText)
For Each singleJsonItem In Json
'What object type is singleJsonItem? To find out, maybe use:
'MsgBox singleJsonItem("imei")
Next singleJsonItem
You have to find out the object type of the collectionentries to extract the JSON Entry.
Solved like this:
used : https://github.com/VBA-tools/VBA-JSON
and named the module: 'mdl_JsonConverter'
Set Json = mdl_JsonConverter.ParseJson(xmlhttp.ResponseText)
For Each item In Json
input_1 = item("input_1")
input_2 = item("input_2")
'THEN DO SOMETHING WITH VALUES F.E. ADDING THEM IN A TABLE
Next
If you responseText contains a searchRecords list then filter by searchRecords before for each
Set Json = JsonConverter.ParseJson(strResponse)
For Each singleJsonItem In Json("searchRecords")
'What object type is singleJsonItem? To find out, maybe use:
Msgbox singleJsonItem("Name")
Next singleJsonItem

What is wrong with this 1 line code?

dim json2=Newtonsoft.Json.Linq.JObject.Parse("[{""currency_code"":""1ST"",""cash"":""0"",""reserved"":""0""},{""currency_code"":""8BT"",""cash"":""0"",""reserved"":""0""}]")
The doublequotes are just escape characters. The actual string is
[{"currency_code":"1ST","cash":"0","reserved":"0"},{"currency_code":"8BT","cash":"0","reserved":"0"}]
Which as you can see is a legitimate json.
Basically it looks like a legitimate json array. I want to turn that into an array of strings
Basically I want to turn that into
{
"{""currency_code"":""1ST"",""cash"":""0"",""reserved"":""0""}",
"{""currency_code"":""8BT"",""cash"":""0"",""reserved"":""0""}"
}
First I parse that into a jobject andd............ I failed.
It's a legitimate json. Why I can't parse that into a jobject?
Some background.
I created 2 json helper function to help me parse any json. One convert json to dictionary. Another parse json into array. In fact, the whole json, is either dictionary (nested or not nested) or array (nested or not nested). Am I correct with this one?
Now the codes are:
Public Shared Function jObjectToDictionary(json As String) As Generic.Dictionary(Of String, String)
Dim json1 = JObject.Parse(json)
Dim dict = json1.ToObject(Of Generic.Dictionary(Of String, Object))
Dim dict2 = dict.ToDictionary(Function(x) x.Key, Function(x) x.Value.ToString)
Return dict2
End Function
Public Shared Function jObjectToArray(json As String) As Generic.List(Of String)
Dim json2 = JObject.Parse(json)
Dim ar = json2.ToObject(Of Generic.List(Of Object))
Dim ar2 = ar.ConvertAll(Function(x) x.ToString)
Return ar2
End Function
The code sort of works.
I then did
Dim jsonar = jsonHelper.jObjectToDictionary(_jsonResult)(starttoken) 'works
Dim ar1 = jsonHelper.jObjectToArray(jsonar) 'doesn't work
Then I examine why jObjectToArray doesn't work and it leads to this one line code that I think should work but doesn't.
That's what I ask. If you can fix this problem of that one line code, I can figure the rest out.
The reason that JObject.Parse is failing is because your JSON represents an array of objects, not just a single object. You can tell because the JSON begins and ends with square brackets [ and ], as opposed to curly braces { and } which denote a single object. To parse an array, you need to use JArray.Parse. (Note you can also use JToken.Parse -- that will parse either a single object or an array.)
Dim json2 = Newtonsoft.Json.Linq.JArray.Parse("[{""currency_code"":""1ST"",""cash"":""0"",""reserved"":""0""},{""currency_code"":""8BT"",""cash"":""0"",""reserved"":""0""}]")
Demo fiddle: https://dotnetfiddle.net/hZlc3m

Get the length of a deserialized object array

I've got following object structure from a JSON deserialization. Then, I can access properly to its values, but how can I get the length of an Object array using a specific key?
I need to get length shown in the picture like jsonDes("result").length.
The following will just print the expected result using VB.NET dynamic features:
Dim jsonDes As Object = New JavaScriptSerializer().DeserializeObject(...)
Dim length As Integer = jsonDes("result").length
Console.WriteLine(length)

Separate JSON objects with JSON.NET (vb)

I am having trouble separating pieces of a JSON object. Inside the json string there are 3 objects. One is called "JSONData", which I need to separate into its own object. I have tried so many things I'm starting to lose track. Two of which that seems to have been most helpful are below. However, they both end up empty. No errors, just empty. Hopefully someone can help!!
Dim j As String = JsonConvert.SerializeXmlNode(xml) 'Started out as XML
Dim o As JObject = JsonConvert.DeserializeObject(j) 'Then Json String to JObject
Dim channel As JObject = DirectCast(o("JSONData"), JObject) 'Try #1 to separate
'/// or
Dim jsondata As String = o.Item("JSONData") 'Try #2
'/// i have tried both above with ("IMSXMLLog.JSONData") as well. Same Result.
https://jsfiddle.net/jharris8567/v23kj42v/ - Full JSON
JSONData is inside another object IMSXMLLog, so your inclination to use the path IMSXMLLog.JSONData is correct. However, the indexer on JToken does not support paths, only single property names. To use path syntax you need to use the SelectToken method:
Dim data as JObject = DirectCast(o.SelectToken("IMSXMLLog.JSONData"), JObject)
Fiddle: https://dotnetfiddle.net/Wu70Tu

Remove JSON object from array

I am using this to serialize my data to object in vb.net Newtonsoft.Json But what I want to do, is to delete object from my event array. The first one (index 0).
I know that can create a class and a list, but the data I get is changing from call to call.
Dim msg As String = Encoding.UTF8.GetString(message.Body)
Dim imgageInfo As Object = JsonConvert.DeserializeObject(Of Object)(msg)
MsgBox(imgageInfo("event")(0)("settings").ToString)
You could deserialize the object into a dictionary and make adjustments to the array from there.
JsonConvert.DeserializeObject<Dictionary<string, string>>(msg);
Maybe a sample of your json would help.