I'm getting mad about this.
I'm very new to Json.
I need to read the array ("items") from the json example provided.
I can read all other objets like "id","title","description"...but not the array of items.
Using Newtonsoft.Jason
Code (vb.net) : >>
Dim json As String = File.ReadAllText("C:\Test\Json\test.json")
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
For Each item As JProperty In data
item.CreateReader()
Select item.Name
Case "results"
For Each comment As JObject In item.Values
txtConsole.Text = comment
Console.WriteLine(comment("id"))
Console.WriteLine(comment("title"))
Console.WriteLine(comment("description"))
Console.WriteLine(comment("tipe"))
Console.WriteLine(comment("author")("description"))
Console.WriteLine(comment("details")("conditions"))
'for each item in array
'Read the array of "products": here
'Console.WriteLine(comment("name")
'Console.WriteLine(comment("codeBar")
'next
Console.WriteLine(comment("details")("benefits"))
Console.WriteLine(comment("details")("price"))
Console.WriteLine(comment("details")("discount"))
Console.WriteLine(comment("details")("pays"))
Console.WriteLine(comment("datefrom"))
Console.WriteLine(comment("dateto"))
Next
End Select
Next
Json file >>
{
"total": 1,
"results": [
{
"id": 208,
"title": "This is the title",
"description": "This is the descripcion",
"tipe": "This is type",
"author": {
"descripcion": "description of author"
},
"details": {
"conditions": {
"items": [
{
"quantity": 6,
"products": [
{
"name": "Product one",
"codeBar": "7891000100103"
},
{
"name": "Product two",
"codeBar": "7894900061604"
},
{
"name": "Product three",
"codeBar": "7894900010015"
},
{
"name": "Product four",
"codeBar": "7894900092011"
}
]
}
]
},
"benefits": null,
"price": null,
"discount": null,
"pays": 5
},
"datefrom": "2015-08-06T00:00:00.000-0300",
"dateto": "2016-12-31T23:59:59.000-0200"
}
]
}
Desire Console output >>
208
This is the title
This is the descripcion
This is type
items
quantity: 6
products
"name": "Product one",
"codeBar": "7891000100103"
"name": "Product two",
"codeBar": "7894900061604"
"name": "Product three",
"codeBar": "7894900010015"
"name": "Product four",
"codeBar": "7894900092011"
5
06/08/2015 00:00:00
31/12/2016 22:59:59
Please, help me...thank u very much in advance !!
This might point you in the right direction. I was able to access the products array this way:
' Open the file using a stream reader.
Dim sr As New StreamReader(System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\json.txt")
Dim line As String
line = sr.ReadToEnd()
line = "[" & line & "]"
Dim jArray__1 = JArray.Parse(line)
For Each item In jArray__1.SelectToken("[0].results.[0].details.conditions.items.[0].products")
MessageBox.Show(item.ToString)
Next
Thak you very much guys !!
I finally did it like this...
For Each element In comment.SelectToken("details")("conditions")("items")(0)("products")
Console.WriteLine(element("name"))
Console.WriteLine(element("codeBar"))
Next
Related
I am trying to map a nested json into a flat file but have an issue referencing between different arrays.
I get it working for each array separately but can't figure out how to properly reference the parent ids to be included. I tried working with indexes and copying the event.id and event.lots.id on the pricings objects but that got really messy.
Maybe I am just on the wrong track or didn't have the right idea on how this might work.
Code
def body = message.getBody(String.class)
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(body)
def i_events = object.events
def i_lots = object.events.lots
def i_pricing = object.events.lots.pricings
def o_values = i_pricing.flatten().collect {"(" + "'" + i_events.collect{it.id}[0] + "'" + "," + "'" + i_lots.collect{it.id}[1] + "'" + "," + "'" + it.id + "'" + "," + "'" +it.name + "'" + ")" }.join(',')
//just using print for testing
println o_values
Result
('event_id1','[id A, id B]','p id1','TEST 1'),('event_id1','[id A, id B]','p id2','TEST 2')
Expected Result
('event_id1','id3','p id1','TEST 1'),('event_id1','id A','p id2','TEST 2')
Sample input
{
"events": [
{
"id": "event_id1",
"name": "Test Event 01",
"to": "2021-08-27T02:30:00.000Z",
"from": "2021-08-26T16:15:00.000Z",
"parkingTo": "2021-08-27T02:30:00.000Z",
"parkingFrom": "2021-08-26T14:15:00.000Z",
"landmarkId": "111",
"slug": "test-event1",
"live": true,
"lots": [
{
"id": "id1",
"name": "Lot 1",
"pricings": []
},
{
"id": "id2",
"name": "Lot 2",
"pricings": []
},
{
"id": "id3",
"name": "Lot3",
"pricings": [
{
"id": "p id1",
"name": "TEST 1"
}
]
}
]
},
{
"id": "event_id2",
"name": "Test Event 2",
"to": "2020-08-31T17:00:00.000Z",
"from": "2020-08-31T14:00:00.000Z",
"parkingTo": "2020-09-01T08:45:00.000Z",
"parkingFrom": "2020-08-31T12:45:00.000Z",
"landmarkId": "111",
"slug": "test-event2",
"live": true,
"lots": [
{
"id": "id A",
"name": "lot A",
"pricings": [
{
"id": "p id2",
"name": "TEST 2"
}
]
},
{
"id": "id B",
"name": "lot B",
"pricings": []
}
]
}
],
"meta": {
"total": 2,
"firstElement": 0,
"lastElement": 2
}
}
Something like this should work (it's hard to say, as your example input seems different to your expected output)
I added a quote method for if the values contain a ', you will need to think if you need this, and how you're going to escape things
def escape(String s) {
"'${s.replaceAll("'", "\\\\'")}'"
}
def output = new JsonSlurper().parseText(body).events.collectMany { event ->
event.lots.collectMany { lot ->
lot.pricings.collect { pricing ->
"(${escape(event.id)}, ${escape(lot.id)}, ${escape(pricing.id)}, ${escape(pricing.name)})"
}
}
}.join(',')
DLL used: Newtonsoft.Json.Linq
When I convert another jason using below converter code it is working fine. but when i am converting given below jason getting error "{"Cannot add a nested relation or an element column to a table containing a SimpleContent column."}". If I replace the 1st seat to seat1 than it is working fine. But I cannot change anything on JSON as this response is shared by 3rd party operator.
Note : I cannot change anything on JSON.
Code:
Dim jsonString = System.IO.File.ReadAllText("D:\Json.txt")
Dim xmlDoc As New XmlDocument
Dim objDS As DataSet
xmlDoc = CType(JsonConvert.DeserializeXmlNode("{""DT"": {" & jsonString.Trim().TrimStart("{").TrimEnd("}") & "} }"), XmlDocument)
objDS = New DataSet()
objDS.ReadXml(New XmlNodeReader(xmlDoc))
JSON:
{
"status":"success",
"msg":"",
"data":{
"block_key":"76570415041123",
"block_time":"7",
"ticket_detail":{
"msrtc":{
"reservation_charge":"5.0",
"asn_amount":"1.0",
"ac_service_charges":"0.0"
},
"upsrtc":"NA",
"hrtc":"NA",
"rsrtc":"NA"
},
"total_fare":280,
"base_fare":274,
"operator_commission_rate":"4.45",
"agent_commission_rate":"85",
"commission_without_gst":8.78,
"agent_tds_value":0.44,
"agent_net_commission":8.34,
"transaction_amount":271.66,
"test":{
"testing":{
"tripchild_con":"Y",
"post_passanger":[
{
"title":"Mr",
"name":"Ram",
"age":"70",
"sex":"M",
"birth":"0",
"seat_no":"45",
"subtotal":"280.0",
"total":"280",
"is_ladies":"false",
"mobile":"9579597539",
"email":"ram#gmail.com",
"id_type":null,
"id_number":null,
"name_on_id":null,
"primary":"True",
"ac":"false",
"sleeper":"false"
}
],
"value":{
"title":"Mr",
"name":"Ram",
"age":"70",
"sex":"M",
"birth":"0",
"seat_no":"45",
"subtotal":"280.0",
"total":"280",
"is_ladies":"false",
"mobile":"9579597539",
"email":"ram#gmail.com",
"id_type":null,
"id_number":null,
"name_on_id":null,
"primary":"True",
"ac":"false",
"sleeper":"false"
},
"senior_citizen_flag":"0",
"seats":{
"seats":[
"2",
"5",
"6",
"9",
"10",
"13",
"14",
"15",
"16",
"17",
"18",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"31",
"32",
"33",
"34",
"35",
"37",
"38",
"39",
"40",
"41",
"42",
"45"
],
"service_id":"724351",
"fare":"280.0",
"childFare":"145.0",
"seniorcitizenfare":"145.0"
},
"passengerDetails":"seniorfare else casse",
"adultFare seniorfare else casse":"274.0",
"tickets_total_basic_fare":274,
"adultFare":null
}
}
}
}
I think that Json structure cannot create Dataset.
So you have to process the data yourself and create it.
see source below
Dim jsonString = System.IO.File.ReadAllText("D:\Json.txt")
Dim dto As TestDTO
dto = JsonConvert.DeserializeObject(Of TestDTO)(jsonString)
MsgBox(dto.status)
Class TestDTO
Property status As String
Property msg As String
Property data As dataDTO
End Class
Class dataDTO
Property block_key As String
Property ticket_detail As ticketdetailDTO
End Class
Class ticketdetailDTO
Property reservation_charge As String
End Class
I am trying to parse a JSON response. I cannot use the VBA-JSON library. I need to check to see if a nested array is empty or null. I keep getting this error:
Example JSON:
{
"gardenAssets": [],
"gardenAssetsAlertCount": 0,
"gardenAssetsCount": 0,
"gardenAssetsErrorCount": 0,
"locationsSummaries": [
{
"locations": [
{
"auditOrder": "102",
"code": "POT 102",
"name": "POT 102",
"type": "ProcessingLocation",
"gardenAssets": [
{
"annotation": "Pallets",
"broker": {
"code": "TMTO",
"isOwner": null,
"name": null
},
"datetimeOfArrivalIngarden": 1622754283.937,
"id": "crusaf",
"isSealable": true,
"load": null,
"mastergardenCode": null,
"name": null,
"owner": {
"code": "SUN",
"isOwner": null,
"name": null
}
}
]
},
{
"auditOrder": "103",
"code": "POT 103",
"description": "POT 103",
"id": "110746",
"name": "POT 103",
"type": "ProcessingLocation",
"gardenAssets": []
},
{
"auditOrder": "104",
"code": "POT 104",
"name": "POT 104",
"gardenAssets": [
{
"annotation": "Soil",
"broker": {
"code": "OTHR",
"isOwner": null,
"name": null
},
"datetimeOfArrivalIngarden": 1622571699.767,
"id": "arserana",
"isSealable": true,
"load": null,
"mastergardenCode": null,
"name": null,
"owner": {
"code": "WTR",
"isOwner": null,
"name": null
}
}
]
},
{
"auditOrder": "111",
"code": "POT 111",
"name": "POT 111",
"type": "ProcessingLocation",
"gardenAssets": [
{
"annotation": null,
"broker": {
"code": "CLD",
"isOwner": null,
"name": null
},
"datetimeOfArrivalIngarden": 1622746446.932,
"id": "Bacrea",
"isSealable": true,
"load": null,
"mastergardenCode": null,
"name": null,
"owner": {
"code": "ICE",
"isOwner": null,
"name": null
},
"status": "EMPTY",
"type": "JUNK",
"unavailable": false,
"visitId": "1003768526"
}
]
}
],
"logingarden": true,
"mastergardenCodes": [],
"gardenCode": "FUN5"
}
],
"offsitegardens": [],
"gardenAssetsInTransit": []}
Code:
Option Explicit
Dim S as Object, k, Ks as Object
Set S = CreateObject("ScriptControl")
S.Language = "JScript"
S.addcode "function k(a){var k=[];for(var b in a){k.push('[\'' + b + '\']');}return k;}"
S.Eval ("var J = " & http.ResponseText)
S.Eval ("var L = J.locationsSummaries['0'].locations")
Set Ks = S.Eval("J.locationsSummaries['0'].locations")
For Each K In Ks
If Not IsNull(S.Eval(K.gardenAssets)) = True Then
Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1) = "Assets"
End If
Next K
I need to pull different information out of the JSON depending on if there are any gardenAssets. But I can't seem to check to see if the array is empty or not.
You can use the length property in JScript.
Dim S As Object
Dim n As Integer, i As Integer, r As Long
r = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1).Row
Set S = CreateObject("ScriptControl")
With S
.Language = "JScript"
.eval "var J = " & http.ResponseText
.eval "var A = J.locationsSummaries['0'].locations"
For n = 1 To S.eval("A.length")
.eval "var L = A[" & n - 1 & "]"
For i = 1 To .eval("L.gardenAssets.length")
Sheet1.Cells(r, 1) = .eval("L.code")
Sheet1.Cells(r, 2) = .eval("L.gardenAssets[" & i - 1 & "].id")
r = r + 1
Next
Next
End With
The example JSON isn't valid. The last member of an object or the last element of an array shouldn't have a comma after it. So where you have:
"broker": {
"code": "TMTO",
"isOwner": null,
"name": null,
}
There shouldn't be a comma after "name": null - there are multiple other errors like this in the example JSON.
You can use an online JSON validator (like this one) to detect these errors. You would ideally want to fix the system that is generating this invalid JSON rather than trying to correct the issues yourself during processing
I have the following JSON:
{
"row2": {
"Activity_log_key": 2,
"Activity_day": "2017-01-12T00:00:00",
"Effort": 8.0,
"Comment": "comment text",
"Activity": "activity text",
"Work_group": "Project",
"Work_item": "test project 1",
"Related_category": {
"Project_phase": [
["category_name", "Design"],
["category_key", 116255]
]
}
},
"row3": {
"Activity_log_key": 3,
"Activity_day": "2017-01-12T00:00:00",
"Effort": 5.5,
"Comment": "no comments",
"Activity": "activty demo text",
"Work_group": "Project",
"Work_item": "project 2",
"Related_category": {
"Project_phase": [
["category_name", "Develop"],
["category_key", 116256]
],
"Training_provider": [
["category_name", "Analysis"],
["category_key", 116254]
]
}
}
}
I convert that JSON response to an object in the controller:
Dim client As New HttpClient
Dim request = client.GetStringAsync(url & "/effort")
request.Wait()
Dim response = request.Result
Dim jsonObj As Object = New JavaScriptSerializer().Deserialize(Of Object)(response)
ViewData("response") = jsonObj
Now I try to run a For Each loop on ViewData("response") in the view but I have no results.
How can I fix that?
Hey I need help in deserializing this:
{
"success": true,
"rgInventory": {
"2722309060": {
"id": "2722309060",
"classid": "939801430",
"instanceid": "188530139",
"amount": "1",
"pos": 1
},
"2722173409": {
"id": "2722173409",
"classid": "937254203",
"instanceid": "188530139",
"amount": "1",
"pos": 2
},
"2721759518": {
"id": "2721759518",
"classid": "720293857",
"instanceid": "188530139",
"amount": "1",
"pos": 3
},
"2721748390": {
"id": "2721748390",
"classid": "310777652",
"instanceid": "480085569",
"amount": "1",
"pos": 4
}
}
}
at the end it should look like:
2722309060#2722173409#2721759518#2721748390
Dim result = JsonConvert.DeserializeObject(jsonstring) 'deserialize it
Dim tempfo As String = result("rgInventory").ToString 'get rgInventory
Console.WriteLine(tempfo)
how i can deserialize all 'id's?
The json contains a Dictionary of items, the IDs you want are the keys. If you deserialized it, you could get them from the Dictionary. Otherwise, you can use JParse and linq to get them:
Dim jstr As String = ...
' parse the json
Dim js As JObject = JObject.Parse(jstr)
' extract the inventory items
Dim ji As JObject = JObject.Parse(js("rgInventory").ToString)
' get and store the keys
Dim theIds As List(Of String) = ji.Properties.Select(Function(k) k.Name).ToList()
I suspect that when "success" is false that the resulting items list will be empty. Test that it works:
For Each s As String In theIds
Console.WriteLine(s)
Next
Result:
2722309060
2722173409
2721759518
2721748390