VbScript Deserialize JSON - json

Using the "ASPJSON" library - http://www.aspjson.com/
I am attempting to get to the "emailAddress" value in the following JSON string
{
"result": {
"lead": [
{
"id": "1",
"emailAddress": "mickey#mouse.com"
},
{
"id": "2",
"emailAddress": "mini#mouse.com"
}
]
},
"error": null,
"id": "1"
}
I am having problems getting to the value using loops, which I believe is the only way to pul out the 2 email addresses.
This is the code I have so far:
For Each result In oJSON.data("result")
Set this = oJSON.data("result")
For Each lead in this("lead")
Set this2 = oJSON.data("active").item(lead)
response.Write("lead") & "<br>"
Next
Next
When I commend out the line
Set this2 = oJSON.data("active").item(lead)
I get 2 lines written by the response.Write so I believe I have got down to the right "level"
But I have failed trying to pull out the values.
The example given by the author of the library looks like this:
But I have been unable to get it to do what I need:
The example JSON:
{
"firstName": "John",
"lastName" : "Smith",
"age" : 25,
"address" :
{
"streetAddress": "21 2nd Street",
"city" : "New York",
"state" : "NY",
"postalCode" : "10021"
},
"phoneNumber":
[
{
"type" : "home",
"number": "212 555-1234"
},
{
"type" : "fax",
"number": "646 555-4567"
}
]
}
And the code example is:
<!--#include virtual="/aspJSON1.17.asp" -->
<%
Set oJSON = New aspJSON
'Load JSON string
oJSON.loadJSON(jsonstring)
'Get single value
Response.Write oJSON.data("firstName") & "<br>"
'Loop through collection
For Each phonenr In oJSON.data("phoneNumber")
Set this = oJSON.data("phoneNumber").item(phonenr)
Response.Write _
this.item("type") & ": " & _
this.item("number") & "<br>"
Next
'Update/Add value
oJSON.data("firstName") = "James"
'Return json string
Response.Write oJSON.JSONoutput()
%>

Finally got it working!
For Each result In oJSON.data("result")("lead")
Set this = oJSON.data("result")("lead").item(result)
response.Write this.item("emailAddress") & "<br>"
Next

Related

ASP classic and Json parse [duplicate]

This question already has an answer here:
Looping though JSON classic ASP
(1 answer)
Closed 10 months ago.
I try to get value out from model_category and others like this in the JSON file.
I use aspJSON1.19.asp and my setup is:
For Each X In oJSON.data("result")
Set this = oJSON.data("result").item(X)
For Each item in this
Response.Write item & " : " & this.item(item) & "<br>"
Next
Next
But I can't get values from items like model_category.
My JSON file contains:
{
"result": [{
"parent": "",
"skip_sync": "false",
"residual_date": "",
"residual": "0",
"sys_updated_on": "2022-04-08 07:41:11",
"request_line": "",
"sys_updated_by": "jan",
"due_in": "",
"model_category": {
"link": "https://hest.service-now.com/api/now/table/cmdb_model_category/57d5bc14c3031000b959fd251eba8fd7",
"value": "57d5bc14c3031000b959fd251eba8fd7"
},
"sys_created_on": "2021-09-28 13:31:33",
"sys_domain": {
"link": "https://hest.service-now.com/api/now/table/sys_user_group/global",
"value": "global"
},
"u_owned_by_company": {
"link": "https://hest.service-now.com/api/now/table/core_company/bff4eaf51b30201075fb7b75464bcb70",
"value": "bff4eaf51b30201075fb7b75464bcb70"
},
"disposal_reason": "",
"model": {
"link": "https://hest.service-now.com/api/now/table/cmdb_model/6a6b3f731bb72050287b7d55464bcb99",
"value": "6a6b3f731bb72050287b7d55464bcb99"
},
"u_correlation_id": "",
"u_scanned_serial_number": "93619031",
"install_date": "",
"gl_account": "",
"invoice_number": "",
"sys_created_by": "manth",
"warranty_expiration": "",
"asset_tag": "",
"depreciated_amount": "0",
"substatus": "available",
"pre_allocated": "false",
"owned_by": "",
"checked_out": "",
"display_name": "Eizo - EV2456",
"sys_domain_path": "/",
"asset_function": "",
"delivery_date": "4010-04-15 12:25:00",
"retirement_date": "",
"beneficiary": "",
"install_status": "6",
"cost_center": "",
"supported_by": "",
"assigned": "",
"purchase_date": "",
"work_notes": "",
"managed_by": "",
"sys_class_name": "alm_hardware",
"sys_id": "01beedbe1bf6f410d37d8735464bcb50",
"po_number": "6202",
"stockroom": {
"link": "https://hest.service-now.com/api/now/table/alm_stockroom/82fd1e941b8fec108d685532604bcba2",
"value": "82fd1e941b8fec108d685532604bcba2"
},
"checked_in": "",
"u_ritm_reference": {
"link": "https://hest.service-now.com/api/now/table/sc_req_item/c7561ab41b72f41075fb7b75464bcb09",
"value": "c7561ab41b72f41075fb7b75464bcb09"
},
"resale_price": "0",
"vendor": "",
"company": "",
"retired": "",
"justification": "",
"department": "",
"expenditure_type": "",
"assigned_to": "",
"depreciation_date": "",
"old_status": "",
"comments": "",
"cost": "0",
"quantity": "1",
"acquisition_method": "",
"sys_mod_count": "5",
"old_substatus": "",
"serial_number": "6677",
"sys_tags": "",
"u_warranty_start": "",
"order_date": "",
"support_group": "",
"reserved_for": "",
"due": "",
"location": {
"link": "https://hest.service-now.com/api/now/table/cmn_location/ef8b8b9b1b20b050287b7d55464bcbbf",
"value": "ef8b8b9b1b20b050287b7d55464bcbbf"
},
"lease_id": "",
"salvage_value": "0"
}]
}
Any help?
That's because model_category is an object (a Scripting.Dictionary), and you can't Response.Write objects directly - you would have to write another For Each loop.
Use a recursive function instead:
Sub PrintJson(item)
Dim key
If IsObject(item) Then
If item Is Nothing Then Exit Sub
If item.Count = 0 Then Exit Sub
Response.Write "<ul class=""jsonObject"">" & vbLf
For Each key In item
Response.Write "<li>" & vbLf
Response.Write Server.HTMLEncode(key) & " : "
PrintJson item(key)
Response.Write "</li>" & vbLf
Next
Response.Write "</ul>" & vbLf
ElseIf IsArray(item) Then
If UBound(item) < 0 Then Exit Sub
Response.Write "<ul class=""jsonArray"">" & vbLf
For key = 0 To UBound(item)
Response.Write "<li>" & vbLf
Response.Write Server.HTMLEncode(key) & " : "
PrintJson item(key)
Response.Write "</li>" & vbLf
Next
Response.Write "</ul>" & vbLf
ElseIf IsNull(item) Then
Response.Write "<span class=""jsonValue""><i>null</i></span>"
Else
Response.Write "<span class=""jsonValue"">"
Response.Write Server.HTMLEncode(item)
Response.Write "</span>"
End If
End Sub
Now you can do this:
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")
oXMLHTTP.Open "GET", "https://....", False
oXMLHTTP.Send
Set oJSON = New aspJSON
oJSON.loadJSON(oXMLHTTP.responseText)
PrintJson oJSON.data
and it will print any nesting level. This is meant as a helper to visualize the content of e.g. a response from an API.
If you know the exact path to an item, and you know that this item exists (!), you can do access it directly
oJSON("result")(0)("model_category")("value")
But this will result in in an error if any of the keys do not exist on the object.

Groovy Collect values from nested json arrays

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(',')

Convert Json to dataset

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

Read Json array vb.net

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

ASPJson and Mandrill API

I am using the aspJSON Class:
http://www.aspjson.com/
To try and write some simple JSON to use for a basic test on the Mandrill email API:
https://mandrillapp.com/api/docs/messages.JSON.html#method=send
I wrote a simple bit of JSON using the "write.asp" example from the aspJSON page via this basic test:
<!--#include file="aspJSON.asp" -->
<%
Set oJSON = New aspJSON
'Write single value
oJSON.data("familyName") = "Smith"
'Make collection
Set oJSON.data("familyMembers") = oJSON.Collection()
'Add instances to collection
Set newitem = oJSON.AddToCollection(oJSON.data("familyMembers"))
newitem.add "firstName", "John"
newitem.add "age", 41
newitem.add "gender", "Male"
Set newitem = oJSON.AddToCollection(oJSON.data("familyMembers"))
newitem.add "firstName", "Suzan"
newitem.add "age", 38
newitem.add "gender", "Female"
Set newitem = oJSON.AddToCollection(oJSON.data("familyMembers"))
newitem.add "firstName", "John Jr."
newitem.add "age", 11
newitem.add "gender", "Male"
'Return the object
Response.Write oJSON.JSONoutput()
%>
That works for quite a "flat" JSON structure which like this:
{
"familyName": "Smith",
"familyMembers":
[
{
"firstName": "John",
"age": 41,
"gender": "Male"
},
{
"firstName": "Suzan",
"age": 38,
"gender": "Female"
},
{
"firstName": "John Jr.",
"age": 11,
"gender": "Male"
}
]
}
But what I'm struggling with is how to write a JSON string like the one shown in the Madrill docs, where the nesting is deeper than shown on the aspJSON example.
For example, this is an extract for the Mandrill JSON string:
{
"key": "example key",
"message": {
"html": "<p>Example HTML content</p>",
"text": "Example text content",
"subject": "example subject",
"from_email": "message.from_email#example.com",
"from_name": "Example Name",
"to": [
{
"email": "recipient.email#example.com",
"name": "Recipient Name",
"type": "to"
}
],
"headers": {
"Reply-To": "message.reply#example.com"
},
"async": false,
"ip_pool": "Main Pool",
"send_at": "example send_at"
}
As you can see for the "to" and "headers" section, the level of nesting is deeper than on the aspJSON example.
I tried this in my ASP code:
<!--#include file="aspJSON.asp" -->
<%
Set oJSON = New aspJSON
'Write single value
oJSON.data("key") = "MY_KEY"
'Make collection
Set oJSON.data("message") = oJSON.Collection()
'Add instances to collection
Set newitem = oJSON.AddToCollection(oJSON.data("message"))
newitem.add "text", "Hello world!"
newitem.add "subject", "Test Subject"
newitem.add "from_email", "me#you.com"
newitem.add "from_name", "Bob Holnas"
Set newitem = oJSON.AddToCollection(oJSON.data("to"))
newitem.add "email", "him#her.com"
newitem.add "name", "Arthur Smith"
newitem.add "type", "to"
Set newitem = oJSON.AddToCollection(oJSON.data("headers"))
newitem.add "Reply-To", "us#them.com"
'Return the object
Response.Write oJSON.JSONoutput()
%>
But got this error:
AddToCollection Error error '800a0001'
Not a collection.
/websites/aspJSON/aspJSON.asp, line 77
I have locally hosted the data from "aspJSON.asp" on my site here:
http://jimpix.co.uk/aspJSON.txt
As it is not available via the aspJSON site.
Any advice would be very much appreciated, as I am really stuck!
Thanks
First let me say I've never used this class before.
After studying the class, I wrote an example and tried to be helpful in the comments.
Hope it helps.
<!--#include file="aspJSON.asp" -->
<%
Set oJSON = New aspJSON
With oJSON.data
.Add "key", "MY_KEY"
.Add "message", oJSON.Collection()
With oJSON.data("message")
.Add "text", "Hello world!"
.Add "subject", "Test Subject"
.Add "from_email", "me#you.com"
.Add "from_name", "Bob Holnas"
.Add "to", oJSON.Collection()
With .Item("to")
'To obtain a collection will be considered an array for output, specify integer keys instead of string
.Add 0, oJSON.Collection() 'first index is a collection
With .Item(0) 'add key-value pairs to first index of the collection
.Add "email", "him#her.com"
.Add "name", "Arthur Smith"
.Add "type", "to"
End With
End With
.Add "headers", oJSON.Collection()
With .Item("headers")
.Add "Reply-To", "us#them.com"
End With
End With
'.Add "async", false
'.Add "ip_pool", "Main Pool"
'.Add "send_at", "example send_at"
End With
Response.Write oJSON.JSONoutput()
%>
Given output:
{
"key": "MY_KEY",
"message": {
"text": "Hello world!",
"subject": "Test Subject",
"from_email": "me#you.com",
"from_name": "Bob Holnas",
"to": [
{
"email": "him#her.com",
"name": "Arthur Smith",
"type": "to"
}
],
"headers": {
"Reply-To": "us#them.com"
}
}
}