Modifying VBA JSON File - json

I want to modify a JSON file in excel using vba.
So I have this JSON file
{
"root": [{
"STATUS_RESPONSE": {
"STATUS": {
"STATUS": {
"OWNER": "root",
}
},
"REQ_ID": "00000",
"RESULT": [{
"USER": {
"BUSINESS_ID": "A",
"USER_NUMBER": "45",
"LANGUAGE": "F",
}
},
{
"USER_SESSION": {
"USER_ID": "0000001009",
"HELP_URL": "http://google.com",
}
},
{
"USER_ACCESS": {
"SERVICES_ROLE": "true",
"JOURNALLING": "true",
}
}]
}
}]
}
I want to modify just the "BUSINESS_ID"
Then I can export to the same JSON file using this
Private Sub CommandButton2_Click()
Dim rng As Range, items As New Collection, myitem As New Dictionary, i As Integer, cell As Variant, myfile As String
Dim FSO As New FileSystemObject
Dim buss As String
Dim JsonTS As TextStream
Set rng = Range("A2")
Set JsonTS = FSO.OpenTextFile("test.json", ForReading)
JsonText = JsonTS.ReadAll
JsonTS.Close
Set JSON = ParseJson(JsonText)
JSON("root")(1)("STATUS_RESPONSE")("RESULT")(1)("USER")("BUSINESS_ID") = Sheets(1).Cells(2, 1).Value
buss = JSON("root")(1)("STATUS_RESPONSE")("RESULT")(1)("USER")("BUSINESS_ID")
myfile = "test.json"
Open myfile For Output As #1
Write #1, buss
Close #1
End Sub
I can edit the cell and this would replace the JSON file but it takes away the whole structure from the JSON file above.
I get something similar to this like in the json file if I change the business id to C:
"C"
Is there a way that I can just modify the thing I need in the existing file without everything else disappearing

You should be exporting the whole JSON object, not just one part of it.
Write #1, JsonConverter.ConvertToJson(JSON, Whitespace:=2)

Related

Loop the contents of a JSON array object

I am new to Vb.net. Having a JSON string as given below, I tries to deserialize the JSON into an Object using JsonConvert.DeserializeObject().
I am trying to loop values inside the Content object in the given JSON to fetch its values.
I tried using a for loop, but I'm not able to get the exact values.
Dim result As String = {
"status": "0001",
"Result": {
"IsError": "0",
"Data": {
"Type": "a",
"Header": [
"v1",
"v2",
"v3",
"v4",
"v5"
],
"Content": [
[
"001",
"Raj",
"1",
"N",
""
],
[
"002",
"Vignesh",
"1",
"N",
""
],
[
"778",
"Ramesh",
"1",
"N",
""
],
[
"792",
"Suresh",
"1",
"N",
""
],
[
"703",
"Karthick",
"1",
"N",
""
],
[
"1247",
"Ram",
"1",
"N",
""
]
]
}
}
}
Dim jsonResult2 = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(result)
If you just want to deserialize the Content array, you can parse the JSON with JToken.Parse(), then deserialize to a List(Of String()) that section only.
Dim jsonResult = JToken.Parse(result)
Dim content = JsonConvert.DeserializeObject(Of List(Of String()))(
jsonResult("Result")("Data")("Content").ToString()
)
Or, you could use a class Model to deserialize the whole JSON, then access each object as a standard .Net Property value.
Public Class StatusResultsRoot
<JsonProperty("status")>
Public Property Status As String
Public Property Result As Result
End Class
Public Partial Class Result
Public Property IsError As String
Public Property Data As Data
End Class
Public Partial Class Data
<JsonProperty("Type")>
Public Property DataType As String
Public Property Header As List(Of String)
Public Property Content As List(Of String())
End Class
'[...]
Dim statusResult = JsonConvert.DeserializeObject(Of StatusResultsRoot)(result)
The Content List is then
Dim content As List(Of String()) = statusResult.Result.Data.Content
' Loop the List of String(), print the combined array of strings
For Each stringArray As String() In content
Console.WriteLine(String.Join(", ", stringArray))
Next
In case you actually want to embed a JSON as a string, you can use an XML element literal, defining an XElement by enclosing the JSON with <node> ... </node> markers.
You can then paste in the JSON as is (no need to double the double-quotes).
The JSON is then the string representation of the first node of the XElement: i.e., [XElement].FirstNode.ToString(). For example:
Dim xResult = <json> {
"status": "0001",
"Result": {
"IsError": "0",
"Data": {
' [... other content ...]
}
}
} </json>
Dim json As String = xResult.FirstNode.ToString()
You cannot do this in C#.
A string in VB must begin and end with a ".
The inner double quotes should be replaced with "".
So a proper string(when assigning it in code) would look like:
Dim result as string = "{
""status"": ""0001"",
...
}
"

Access nested values in JSON-Object in VBA

I would like to get data from a JSON-Object, that I got from a Rest-API, with VBA to display some data into an Excel-Worksheet. I'm using the library (VBA-JSON v2.3.1 JsonConverter).
I have the following JSON-Object:
{
"devices": [
{
"data": [
{
"id": 0,
"name": "Hello"
},
{
"id": 1,
"name": "How are you?"
},
{
"id": 2,
"name": "Bye"
}
],
"type": "LORA"
}
],
"includedTypes": [
"LORA"
]
}
I want to get the objects in the array from "data".
My VBA-Code is this:
Dim js1Object As Object
Dim response1 As String
strUrl = "https://XXXXXXXXXXXdevices
Set hReq = CreateObject("MSXML2.XMLHTTP")
With hReq
.Open "GET", strUrl, False
.SetRequestHeader "Authorization", "Bearer " & apitoken
.Send
response1 = hReq.responseText
MsgBox response1
Set js1Object = JsonConverter.ParseJson(response1)
j = 31
For Each item In js1Object("devices")
ws.Cells(j, 7) = item("id")
ws.Cells(j, 10) = item("name")
j = j + 1
Next
MsgBox (response1)
End With
How can I access the values from "data"?
If the JSON would look like the object below, my code would work. But my problem is, that the response that I get, is more nested and I can't directly access "data".
{
"devices": [
{
"id": 0,
"name": "Hello"
},
{
"id": 1,
"name": "How are you?"
},
{
"id": 2,
"name": "Bye"
}
]
}
I just don't know, how to access deeper values in JSON-Object. The solutions from similar questions with print are not working with my code.
Thanks for helping me!
Your "root" json object is a Dictionary - the key "devices" is a Collection object, and the first element is another dictionary with two keys "data" and "type".
"data" is another Collection of Dictionaries, so you can do this to get to the contained id and name values:
Dim Json As Object, data, d
'reading json from a worksheet cell...
Set Json = JsonConverter.ParseJson(Range("A5").Value)
Set data = Json("devices")(1)("data") 'Dictionary key->Collection index->Dictionary key
For Each d In data
Debug.Print d("id"), d("name")
Next d
Output:
0 Hello
1 How are you?
2 Bye

issue with Retrieve original value from json

New Help to retrieve original value from Json row Data the below code strip some "\"
-------------Json data-----------------
{
"type": "push",
"targets": ["stream"],
"push": {
"type": "mirror",
"source_device_iden": "ujzp6Xr9A4asjyjskXPzu8",
"source_user_iden": "ujzp6Xr9A4a",
"client_version": 354,
"dismissible": true,
"icon": "test",
"title": "ok",
"body": "Hi",
"application_name": "android",
"package_name": "com.android",
"notification_id": "1",
"notification_tag": "y9x5Q2YAI\/pqPhZwbaN6TpoW4eJhe0kAe0HfmWOQyWA=\n",
"conversation_iden": "{\"package_name\":\"com.android\",\"tag\":\"y9x5Q2YAI\\\/pqPhZwbaN6TpoW4eJhe0kAe0HfmWOQyWA=\\n\",\"id\":1}"
}
}
-------------------- VB code ---------------------------
Private Sub jsonData(JsonStr As String)
Dim json As String = JsonStr
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim Result as string
For Each item As JProperty In data
item.CreateReader()
Select Case item.Name
Case "push"
For Each msg As JObject In item
Result = msg("conversation_iden")
Next
End Select
Next
End Sub
--------------------------- resulet -----------------------------
Result = "{"package_name":"com.com.android","tag":"y9x5Q2YAI/pqPhZwbaN6TpoW4eJhe0kAe0HfmWOQyWA=\n","id":1}"
original value :
"{\"package_name\":\"com.android\",\"tag\":\"y9x5Q2YAI\/pqPhZwbaN6TpoW4eJhe0kAe0HfmWOQyWA=\n\",\"id\":1}"

Deserialized an object into a DataTable

I have a JSON response like this:
{ "cod": "OK",
"list": [
{ "date": "31\/10\/2018", "count": "109", "name": "PAUL" },
{ "date": "30\/09\/2018", "count": "103", "name": "LUKE" }
]}
I use:
Dim jss As New JavaScriptSerializer
Dim Response = jss.Deserialize(Of Object)(strResponse)
Dim Cod = Response("cod")
Then:
Dim Lista_documents = Response("list")
And I have an object with the list of documents.
How can I populate a new DataTable?
I am not aware of any methods that will do it automatically, so probably with a Loop.
Dim table As New DataTable
table.Columns.Add("date", GetType(Date))
table.Columns.Add("count", GetType(Integer))
table.Columns.Add("name", GetType(String))
For Each Li In Lista_documents
table.Rows.Add(Li("date"), Li("count"), Li("name"))
Next
Adjust depending on how your Lista_documents is structured

Adding to existing JSON from excel

I want to add to this JSON file in excel using vba.
So I have this JSON file
{
"root": [{
"STATUS_RESPONSE": {
"STATUS": {
"STATUS": {
"OWNER": "root"
}
},
"REQ_ID": "00000",
"RESULT": [{
"USER": {
"BUSINESS_ID": "A",
"USER_NUMBER": "45",
"LANGUAGE": "F"
}
},
{
"USER_SESSION": {
"USER_ID": "0000001009",
"HELP_URL": "http://google.com"
}
},
{
"USER_ACCESS": {
"SERVICES_ROLE": "true",
"JOURNALLING": "true"
}
}]
}
}]
}
I want to add another "USER" right below it so it looks like
{
"root": [{
"STATUS_RESPONSE": {
"STATUS": {
"STATUS": {
"OWNER": "root"
}
},
"REQ_ID": "00000",
"RESULT": [{
"USER": {
"BUSINESS_ID": "A",
"USER_NUMBER": "45",
"LANGUAGE": "F"
}
},
{
"USER": {
"BUSINESS_ID": "B",
"USER_NUMBER": "55",
"LANGUAGE": "E"
}
},
{
"USER_SESSION": {
"USER_ID": "0000001009",
"HELP_URL": "http://google.com"
}
},
{
"USER_ACCESS": {
"SERVICES_ROLE": "true",
"JOURNALLING": "true"
}
}]
}
}]
}
This is what I have currently
Private Sub CommandButton3_Click()
Dim z As Integer, items As New Collection, myitem As New Dictionary
Dim rng As Range
Dim cell As Variant
Dim FSO As New FileSystemObject
Dim JsonTS As TextStream
Set JsonTS = FSO.OpenTextFile("test.json", ForReading)
JsonText = JsonTS.ReadAll
JsonTS.Close
Set JSON = ParseJson(JsonText)
Set rng = Range("A5")
z = 0
For Each cell In rng
myitem("BUSINESS_ID") = cell.Offset(0, 1).Value
myitem("USER_NUMBER") = cell.Offset(0, 2).Value
myitem("LANGUAGE") = cell.Offset(0, 3).Value
items.Add myitem
Set myitem = Nothing
z = z + 1
Next
myfile = Application.ActiveWorkbook.Path & "\test.json"
Open myfile For Output As #1
Print #1, ConvertToJson(myitem, Whitespace:=2)
MsgBox ("Exported to JSON file")
Close #1
End Sub
All this does is add it below the existing JSON and is not connected to it all.
How would I go about add another "USER" right below the current one with the information from excel