ASPJson and Mandrill API - json

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

Related

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

How to get values from json string with aspJSON.asp? [duplicate]

This question already has answers here:
ASP JSON: Object not a collection
(2 answers)
Closed 2 years ago.
I have this JSON and no matter what I try I can´t get any values from it. I don´t know what Im missing?
This is the json string.
{
"groups": [{
"name": "Credit Card",
"types": ["mc", "visa", "amex"]
}],
"paymentMethods": [{
"brands": ["mc", "visa", "amex"],
"details": [{
"key": "encryptedCardNumber",
"type": "cardToken"
}, {
"key": "encryptedSecurityCode",
"type": "cardToken"
}, {
"key": "encryptedExpiryMonth",
"type": "cardToken"
}, {
"key": "encryptedExpiryYear",
"type": "cardToken"
}, {
"key": "holderName",
"optional": true,
"type": "text"
}],
"name": "Card",
"type": "scheme"
}, {
"name": "Få först. Betala sen med Klarna.",
"supportsRecurring": true,
"type": "klarna"
}, {
"name": "Trustly",
"supportsRecurring": true,
"type": "trustly"
}, {
"name": "Swish",
"supportsRecurring": true,
"type": "swish"
}, {
"name": "Paysafecard",
"supportsRecurring": true,
"type": "paysafecard"
}, {
"name": "Dela upp med Klarna.",
"supportsRecurring": true,
"type": "klarna_account"
}, {
"name": "Pay now with Klarna.",
"supportsRecurring": true,
"type": "klarna_paynow"
}]
}
And then I try to get one single value(the "Credit Card") and also loop through all the paymetsMethods.details.key values and then loop all the last "name".
<!--#include file="aspJSON1.17.asp" -->
jsonstring = CStr(objXmlHttp.ResponseText)
'response.write "---"&jsonstring &"---"
Set oJSON = New aspJSON
oJSON.loadJSON(jsonstring)
groupsname=oJSON.data("groups").item("name")
response.write groupsname
For Each x In oJSON.data("paymentMethods").item("details")
paymentMethods=oJSON.data("paymentMethods").item("details").item("key")
response.write paymentMethods
NEXT
For Each x In oJSON.data("name")
thename=oJSON.data.item("name")
response.write thename
NEXT
Im clearly missing something, but what?
When parsing JSON if you come across a collection (i.e. an Array) you have to iterate through it before trying to retrieve values deeper in the JSON structure.
In this case, to get to the key property you have to iterate through two collections.
paymentMethods
details
So this For loop;
For Each x In oJSON.data("paymentMethods").item("details")
paymentMethods=oJSON.data("paymentMethods").item("details").item("key")
response.write paymentMethods
NEXT
Should look more like;
Dim paymentMethod, paymentMethodsItem, details, detailsItem
For Each paymentMethodsItem In oJSON.data("paymentMethods")
Set paymentMethod = oJSON.data("paymentMethods").item(paymentMethodsItem)
For Each detailsItem In paymentMethod.data("details")
Set details = paymentMethod.data("details").item(detailsItem)
Call Response.Write(details.item("key"))
Next
Next
#Code provided untested
Useful Links
Looping though JSON classic ASP
ASP JSON: Object not a collection

VBA: count items in JSON response string / trello get Cards count in a List

I'm using VBA-web (https://vba-tools.github.io/VBA-Web/) to access trello api, to get cards in a list
My function looks like that:
Public Function CountCardsinList(ListId As String) As Integer
WebHelpers.EnableLogging = False
Dim TrelloClient As New WebClient
TrelloClient.BaseUrl = "https://api.trello.com/1/"
Dim Request As New WebRequest
Request.Format = WebFormat.Json
Request.ResponseFormat = Json
Request.Resource = "lists/{ListId}/cards"
Request.AddUrlSegment "ListId", ListId
Request.AddQuerystringParam "key", TrelloAPIKey
Request.AddQuerystringParam "token", TrelloAPIToken
Request.AddQuerystringParam "filter", "open"
Dim Response As WebResponse
Set Response = TrelloClient.Execute(Request)
If Response.StatusCode = WebStatusCode.Ok Then
Debug.Print Response.Content '
'Response.Data("idList").Count
Debug.Print "CountCardsinList =>>> " & Response.Content
CountCardsinList = Response.Data("idList").Count
Else
MsgBox Response.StatusDescription, vbCritical, "Error " & Response.StatusCode
CountCardsinList = ""
End If
Debug.Print "CountCardsinList =>>> " & Response.Content
'Set CountCardsinList = Request
End Function
I receive correct JSON reply from the api:
[{
"id": "584e798dd570ae187b293e5b",
"checkItemStates": null,
"closed": false,
"dateLastActivity": "2016-12-30T09:24:57.531Z",
"desc": "",
"descData": null,
"idBoard": "57873ba94794058756fa0a96",
"idList": "57873bb3a725f734089702b2",
"idMembersVoted": [],
"idShort": 90,
"idAttachmentCover": null,
"manualCoverAttachment": false,
"idLabels": ["57873ba984e677fd3683bef8"],
"name": "card name / other stuff",
"pos": 1999.9923706054688,
"shortLink": "izoqvWJk",
"badges": {
"votes": 0,
"viewingMemberVoted": false,
"subscribed": false,
"fogbugz": "",
"checkItems": 0,
"checkItemsChecked": 0,
"comments": 0,
"attachments": 0,
"description": false,
"due": "2016-12-26T11:00:00.000Z",
"dueComplete": false
},
"dueComplete": false,
"due": "2016-12-26T11:00:00.000Z",
"idChecklists": [],
"idMembers": ["54f0cc079bf18f2798dda8bd"],
"labels": [{
"id": "57873ba984e677fd3683bef8",
"idBoard": "57873ba94794058756fa0a96",
"name": "Urgent",
"color": "red",
"uses": 14
}],
"shortUrl": "https://trello.com/c/vfvfdvdfv",
"subscribed": false,
"url": "https://trello.com/c/fdvfdvdfv/cfvdfv"
},
{
"id": "5832c2fa7f55fe5637d972ea",
"checkItemStates": null,
"closed": false,
"dateLastActivity": "2016-12-30T09:25:09.222Z",
"desc": "",
"descData": null,
"idBoard": "57873ba94794058756fa0a96",
"idList": "57873bb3a725f734089702b2",
"idMembersVoted": [],
"idShort": 80,
"idAttachmentCover": null,
"manualCoverAttachment": false,
"idLabels": ["57873ba984e677fd3683bef6"],
"name": "other card name",
"pos": 2023.9922790527344,
"shortLink": "XhUPgcsD",
"badges": {
"votes": 0,
"viewingMemberVoted": false,
"subscribed": false,
"fogbugz": "",
"checkItems": 0,
"checkItemsChecked": 0,
"comments": 0,
"attachments": 0,
"description": false,
"due": "2016-12-30T15:00:00.000Z",
"dueComplete": false
},
"dueComplete": false,
"due": "2016-12-30T15:00:00.000Z",
"idChecklists": [],
"idMembers": ["54fdbe1a8ecdf184596c7c07"],
"labels": [{
"id": "57873ba984e677fd3683bef6",
"idBoard": "57873ba94794058756fa0a96",
"name": "Medium",
"color": "yellow",
"uses": 1
}],
"shortUrl": "https://trello.com/c/XhdfvdfvUPgcsD",
"subscribed": false,
"url": "https://trello.com/c/XhUPgcsfdvdffvD/
"
But I cannot correctly count idList -> and I'm trying to get number of cards in a list, by using Response.Data("idList").Count
Any information how to do it proper way? or which is the best way to parse JSON data?
General:
Your JSON isn't properly closed. I added }] to the end to close and placed in cell A1 of activesheet (as I don't have the API info). I then read that in from the cell as if it were response text.
Process:
I then used JSONConverter to parse this string from the sheet. This requires you to also add a reference to Microsoft Scripting Runtime via VBE > Tools > References.
The returned object is a collection of dictionaries. I test each dictionary for the existence of an idList key and if present add 1 to the variable itemCount, which keeps track of how many idLists there are.
Code:
Public Sub GetInfoFromSheet()
Dim jsonStr As String, item As Object, json As Object, itemCount As Long
jsonStr = [A1]
Set json = JsonConverter.ParseJson(jsonStr)
For Each item In json 'collection
If item.Exists("idList") Then itemCount = itemCount + 1
Next item
Debug.Print "idList count: " & itemCount
End Sub

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

hitting REST web service from vbscript

I'm using vbscript to test a REST web service which accepts json as request and responds also in json format. I'm getting HTTP 500 - Internal Server Error as response. Here's the code:
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("C:\request.txt")
restRequest = objStream.ReadText()
objStream.Close
Set objStream = Nothing
contentType ="application/json"
Set oWinHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
oWinHttp.Open "POST", "http://czcholsint1048.prg-dc.dhl.com:8180/efoms/fulfillOrder", False
oWinHttp.setRequestHeader "Content-Type", contentType
oWinHttp.Send restRequest
response = oWinHttp.StatusText
'response' turns out as "Internal Server Error"
I just wonder whether the json i'm converting to string before sending as request is creating any problem. Maybe beacuse of vbcrlf's it has.
Below is the json i'm sending as request:
{
"fulfillOrderReq": {
"hdr": {
"messageType": "SALESORDER",
"messageID": "d264502f-aaa2-42a5-a38d-c981ccb99379", "messageVersion": "0.1",
"messageDateTime": "2015-03-20 09:48:29",
"appId": "OMS",
"clientId": "PEP-ESB",
"reqCompId": "77000001"
},
"bd": {
"orders": [
{
"order": {
"orderNumber": "BAYLINETEST512",
"salesChannelOrderNumber": "TMALLTEST512",
"shopName": "拜仁慕尼黑海外旗舰店",
"salesChannel": "天猫订单",
"payType": "支付宝",
"created": "2015-03-20 15:35:58",
"salesChannelMemberName": "mariahliu621",
"salesChannelMemberNo": "M-9837423",
"idCard": "12312",
"idType": "NATIONAL_IDENTIFICATION_NUMBER",
"cnee": {
"name": "SANTOSH",
"address1": "CHINA",
"address3": "CHINA",
"state": "CHINA",
"city": "CHINA",
"country": "CN",
"postCode": "50470",
"telephone": "18610041036",
"mobilePhone": "18610041036"
},
"cneeMemo": "",
"cneeMessage": "",
"sellerMemo": "",
"otherMemo": "",
"actualOrderAmount": "792.0",
"agioAmount": "0.0",
"discountFee": "0.0",
"deliveryCost": "70.0",
"promotionInfo": "",
"orderItems": [
{
"orderItem": {
"productNumber": "184005",
"productName": "蜂拥而至CL克 Flock CL gr.",
"skuNumber": "184005",
"skuName": "Ribéry",
"barcode": "",
"orderGroup": "0",
"productQty": "1",
"amount": "75.0",
"discountFee": "0.0",
"agioPrice": "90.0",
"price": "110.0",
"taxCharges": "100",
"untaxPrice": "50",
"dutyCharges": "9",
"refundStatus": "Normal",
"memo": ""
}
}
]
}
}
]
}
}
}
You may have seen this already however wanted to share this here since they are related. http://forum.universal-devices.com/topic/4335-vbscript-rest-example/
Option Explicit
Dim restReq, url, userName, password
Set restReq = CreateObject("Microsoft.XMLHTTP")
' Replace <node> with the address of your INSTEON device
' Additionally, any REST command will work here
url = "http://isy/rest/nodes/<node>/ST"
' If auth is required, replace the userName and password values
' with the ones you use on your ISY
userName = "admin"
password = "<yourpassword>"
restReq.open "GET", url, false, userName, password
restReq.send
WScript.echo restReq.responseText