issue with Retrieve original value from json - 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}"

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"",
...
}
"

What is the easiest way to get a value in JSON array based on another value?

Here is my JSON:
{
"contacts": [{
"identity-profiles": [{
"identities": [{
"type": "EMAIL",
"value": "twitterman#twitter.com",
"timestamp": 1531322937327,
"is-primary": true
}, {
"type": "LEAD_GUID",
"value": "10000-10000-10000-10000",
"timestamp": 1531322937344
}]
}],
},
}
I would like to get the value WHERE the type = "Email". My problem is, it may appear as below so it's not always the same order as above:
{
"contacts": [{
"identity-profiles": [{
"identities": [{
"type": "LEAD_GUID",
"value": "10000-10000-10000-10000",
"timestamp": 1531322937344
}, {
"type": "EMAIL",
"value": "twitterman#twitter.com",
"timestamp": 1531322937327,
"is-primary": true
}]
}],
},
}
This is currently my VB code which only gives me the value that comes first in the JSON array:
For Each item In jcontacts.ToList()
Dim portalId = item("portal-id").ToString()
Dim associatedCompanyId = If(item("properties")("associatedcompanyid")?("value").ToString, DBNull.Value)
Dim contactId = item("vid").ToString()
Dim firstName = If(item("properties")("firstname")?("value").ToString(), DBNull.Value)
Dim lastName = If(item("properties")("lastname")?("value").ToString(), DBNull.Value)
Dim email = If(item("identity-profiles")(0)("identities")?("value").ToString(), DBNull.Value)
Dim telephone = If(item("properties")("phone")?("value").ToString(), DBNull.Value)
Dim createDate = If(item("addedAt").ToString(), DBNull.Value)
Dim modifiedDate = If(item("properties")("lastmodifieddate")?("value").ToString(), DBNull.Value)
Next
Thanks in advance.
Thanks to #ADyson for pointing me in the right direction. This is my loop now:
For Each item In jcontacts.ToList()
Dim portalId = item("portal-id").ToString()
Dim associatedCompanyId = If(item("properties")("associatedcompanyid")?("value").ToString, DBNull.Value)
Dim contactId = item("vid").ToString()
Dim firstName = If(item("properties")("firstname")?("value").ToString(), DBNull.Value)
Dim lastName = If(item("properties")("lastname")?("value").ToString(), DBNull.Value)
Dim email = Nothing
Dim profile = item("identity-profiles")(0)("identities")
For Each sitem In profile
If (sitem("type").ToString() = "EMAIL") Then
email = sitem("value").ToString()
Exit For
Else
email = DBNull.Value
End If
Next
Dim telephone = If(item("properties")("phone")?("value").ToString(), DBNull.Value)
Dim createDate = If(item("addedAt").ToString(), DBNull.Value)
Dim modifiedDate = If(item("properties")("lastmodifieddate")?("value").ToString(), DBNull.Value)
Next

Modifying VBA JSON File

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)

vb.net get values from json like string in DataTable

Here is my json like string:
{
"ProductGroupId": "3",
"ProductGroupName": "Frisdranken",
"ProductId": "139",
"ProductName": "Cola",
"Quantity": 1,
"QuantityUnit": "P",
"SellingPrice": 2.7,
"VatRateId": "A",
"DiscountLines": []
}, {
"ProductGroupId": "3",
"ProductGroupName": "Frisdranken",
"ProductId": "146",
"ProductName": "Plat water",
"Quantity": 1,
"QuantityUnit": "P",
"SellingPrice": 2.6,
"VatRateId": "A",
"DiscountLines": []
}
How do I get the "ProductName" and "Quantity" in a datatable?
Assuming your json is an array and you just missed the enclosing [...], you can:
Dim json As String = "[{""ProductGroupId"":""3"",""ProductGroupName"":""Frisdranken"",""ProductId"":""139"",""ProductName"":""Cola"",""Quantity"":1,""QuantityUnit"":""P"",""SellingPrice"":2.7,""VatRateId"":""A"",""DiscountLines"":[]},{""ProductGroupId"":""3"",""ProductGroupName"":""Frisdranken"",""ProductId"":""146"",""ProductName"":""Plat water"",""Quantity"":1,""QuantityUnit"":""P"",""SellingPrice"":2.6,""VatRateId"":""A"",""DiscountLines"":[]}]"
'Use JSON.Net to obtain a JArray
Dim jobj As JArray = JsonConvert.DeserializeObject(json)
'Extract just the fields you want from the data with a Linq projection into
'anonymous type with ProductName and Quantity fields
Dim ProductsAndQuantities = jobj.Select(Function(j)
Return New With {
.ProductName = j("ProductName"),
.Quantity = j("Quantity")}
End Function)
'build your DataTable
Dim dt As DataTable = New DataTable()
dt.Columns.Add("ProductName")
dt.Columns.Add("Quantity")
'Load the data table
For Each item In ProductsAndQuantities
Dim dr As DataRow = dt.NewRow()
dr("ProductName") = item.ProductName
dr("Quantity") = item.Quantity
dt.Rows.Add(dr)
Next

looping over items and access property of a parsed json object

OK i know how to parse using newtonsoft.
but I don't know how can i get every value of key inside parsed string
this is the json encoded string
{"result":[{"orderid":"94","imei":"clipper"},{"orderid":"93","item":"shoes"},{"orderid":"92","item":"bag"},{"orderid":"91","item":"shirt"}]}
Dim xreadingJson = Newtonsoft.Json.Linq.JObject.Parse(htmlcode)
Dim resultorder As String = xreadingJson.Item("result").ToString
then the result order is
[
{
"orderid": "94",
"item": "clipper"
},
{
"orderid": "93",
"item": "shoes"
},
{
"orderid": "92",
"item": "shoes"
},
{
"orderid": "91",
"item": "bag"
}
]
On looping how can I get the value of orderid and item.
thank you
Update:
I resolved it using this code
Dim o As JObject = JObject.Parse(htmlcode)
Dim results As List(Of JToken) = o.Children().ToList
For Each item As JProperty In results
item.CreateReader()
'MsgBox(item.Value)
If item.Value.Type = JTokenType.Array Then
For Each subitem As JObject In item.Values
MsgBox(subitem("orderid"))
MsgBox(subitem("item"))
Next
End If
Next
I believe Newtonsoft's JObject has a JObject.GetValue("property_name") method