I am working with the Google Translation API, which returns results in JSON format - e.g.
{
"data": {
"translations": [
{
"translatedText": "Hola mundo"
},
{
"translatedText": "Te amo"
},
{
"translatedText": "queso"
}
]
}
}
I am trying to parse the JSON data using Classic ASP.
I'm using ASPJSON (http://www.aspjson.com/) to parse the JSON data.
I can get so far with reading the data - e.g. (where "BackFromGoogle") is the objXML.responseText from a MSXML2.ServerXMLHTTP call.
Set oJSON = New aspJSON
oJSON.loadJSON(BackFromGoogle)
For Each translation In oJSON.data("data") 'iterate through data
Set this = oJSON.data("data").item(translation)
Next
If I then try:
For Each translation In oJSON.data("data") 'iterate through data
Set this = oJSON.data("data").item(translation)
Response.Write this.item("translations").item("translatedText")
Next
Then I get this error:
Microsoft VBScript runtime error '800a01a8'
Object required: '[undefined]'
For this line:
Response.Write this.item("translations").item("translatedText")
I am very stuck working out the syntax to allow me to access the individual values of the "translatedText" lines.
Is it possible to access them?
Got this working in the end.
Found the answer via the solution here:
VbScript Deserialize JSON
This sorted it:
Set oJSON = New aspJSON
oJSON.loadJSON(BackFromGoogle)
For Each result In oJSON.data("data")("translations")
Set this = oJSON.data("data")("translations").item(result)
response.Write this.item("translatedText") & "<br>"
Next
Related
Has anyone an idea how to loop JSON string and get all data by JSON key? I have very heavy JSON file with arrays in arrays in array.
{
"ID":"33",
"A":a,
"SUB-ID": [
{ "ID":"33"},
{ "A":"b"},
{ "SUB-ID":[] }
]
"ID":"37",
"A":a,
"SUB-ID": [
{ "ID":"38"},
{ "A":"b"},
{ "SUB-ID":[] }
]
"ID":"39",
"A":a,
"SUB-ID": [
{ "ID":"31"},
{ "A":"b"},
{ "SUB-ID":["ID":"30",SUB-ID[...]] } 'And this array in array "Sub-ID" - there may be more below each other
]
}
In Sub-Id can be infinite loop arrays....
This JSON can have lot of sub-arrays... And i need to get list of all IDs.
You do not need to loop through aka manually parse json text to create your object. Go to your nugent packages and download Newtonsoft json and add it to your project.
Now if you have a class written with that object You can now call the following:
Dim myJsonText as string = (your json text)
Dim myJsonObject as new (whatever your object name is)
MyJsonObject = JsonConvert.DeserializeObject(myJsonText, GetType(yourobjectName))
It will now create your object and now you can assign your object properties like this.
MyJsonObject.ID = 3
MyJsonObject.A=“A”
If you need to convert it back to json text you call the following:
MyJsonText = jsonConvert.SERIALIZEObject(myJsonObject)
My question is about a JSON file, of which I'm getting errors when putting certain values in a text component.
{
"response": {
"game_count": 4,
"games": [
{
"appid": 10,
"playtime_forever": 0
},
{
"appid": 20,
"playtime_forever": 0
},
{
"appid": 30,
"playtime_forever": 0
},
{
"appid": 40,
"playtime_forever": 0
}
]
}
}
I'm trying to get the values "10,20,30,40" from "appid" in a RichTextBox, one below the other. For this, I am using this code:
JsonString = file
Dim jsonObject As JObject = JObject.Parse(JsonString)
Dim JsonArray As JArray = JArray.Parse(jsonObject.SelectToken("games").ToString)
For Each item As JObject In JsonArray
RichTextBox2.Text = item.SelectToken("appid").ToString
Next
But I'm getting the following error in line 4 of the above code:
Object reference not set to an instance of an object
Is there a way to fix this? I believe my code is right. I'm using the NewtonSoft library.
You can use SelectTokens("..appid") to recursively descent the JSON token hierarchy and find values of properties named "appid", where ".." is the JSONPath recursive descent operator:
Dim jsonObject As JToken = JToken.Parse(JsonString)
Dim appids = jsonObject _
.SelectTokens("..appid") _
.Select(Function(t) CType(t, Long)) _
.ToList()
After finding all "appid" values I cast then to Long using an explicit conversion cast. You could cast to Int If you are certain that all appid values will be less than Int.MaxValue. Or you could cast then to String if you're not interested in the numeric values.
Working .Net fiddle.
So I have a request to a JSON api working using client-side jquery and AJAX. Unfortunately, another api insists this be done from the server because of security concerns regarding the token. I'm a bit stumped. To begin, what I got working from client-side JavaScript looks like:
$.getJSON("https://api.xyz.com/mytoken/specificargument",function(data){...})
The function then fills data with JSON fields (or are they called properties?) as data.field1, data.field2, etc. These are then placed into their appropriate inputs with jquery code that lives inside the {...}. It's very straightforward.
I have read that this (i.e., obtaining the JSON string, not parsing it) can be done on the server with
Set objJSON = jsObject()
objJSON("apikey") = "mytoken"
Set objJSON("arg1") = jsObject()
objJSON("arg1")("arg1") = "specificargument"
set objXMLhttp = Sever.Createobject("MSXML2.ServerXMLHTTP")
objXMLhttp.open "POST","https://api.abc.com", false
objXMLhttp.setRequestHeader "Content-type","application/json"
objXMLhttp.setRequestHeader "Accept","application/json"
objXMLhttp.send objJSON.jsString
strResponse = objXMLhttp.responseText
Set objXMLhttp = Nothing
So that's pretty useful, except the posting says I need to use "appropriate declarations, includes, etc." So I thought it would be simple to find these, but querying for classic ASP JSON yields very confusing results. Can someone help with these:
what do I need to do to properly use the aspjson library for the above?
how do I pass "specificargument" above. What I've written is a bit of a mess and I'm sure incorrect. On the client side, the token and argument are part of the querystring. How does this work for the jsObject?
Thank you.
The example code you have posted appears to be using the aspjson - JSON serializer for VBScript based ASP server technology library. One key thing in that statement is "JSON Serializer", it will only serialise from object to string, not the other way around which makes it kind of useless for most scenarios.
This is purely my opinion but a well-maintained library that will do both is JSON object class By RCDMK. The examples on the GitHub page are pretty simple to follow, but there are some examples of its usage on this very site.
Here is a quick example of its usage inside an ASP page;
<% Option Explicit %>
<!-- #include virtual="/scripts/jsonObject.class.asp" -->
<%
Dim JSON, parsedJSON
Dim jsonString: jsonString = "[{ ""strings"" : ""valorTexto"", ""numbers"": 123.456, ""arrays"": [1, ""2"", 3.4, [5, 6, [7, 8]]], ""objects"": { ""prop1"": ""outroTexto"", ""prop2"": [ { ""id"": 1, ""name"": ""item1"" }, { ""id"": 2, ""name"": ""item2"", ""teste"": { ""maisum"": [1, 2, 3] } } ] } }]"
Call init()
Sub init()
Response.LCID = 2057
Set JSON = New JSONobject
Call Response.Write("<h2>JSON String</h2>")
Call Response.Write("<pre>" & jsonString & "</pre>")
Call Test_ParseJSON()
Call Test_WriteJSON()
End Sub
Sub Test_ParseJSON()
Call Response.Write("<h2>Parsing JSON</h2>")
Set parsedJSON = JSON.Parse(jsonString)
Call Response.Write("<pre>parsedJSON(0).Value(""objects"").Value(""prop1"") = """ & parsedJSON(0).Value("objects").Value("prop1") & """</pre>")
End Sub
Sub Test_WriteJSON()
Call Response.Write("<h2>Writing JSON</h2>")
Call parsedJSON(0).Value("objects").Change("prop1", "hello test")
Call Response.Write("<pre>" & parsedJSON.Serialize() & "</pre>")
End Sub
%>
Outputs:
JSON String
[{ "strings" : "valorTexto", "numbers": 123.456, "arrays": [1, "2", 3.4, [5, 6, [7, 8]]], "objects": { "prop1": "outroTexto", "prop2": [ { "id": 1, "name": "item1" }, { "id": 2, "name": "item2", "teste": { "maisum": [1, 2, 3] } } ] } }]
Parsing JSON
parsedJSON(0).Value("objects").Value("prop1") = "outroTexto"
Writing JSON
[{"strings":"valorTexto","numbers":123.456,"arrays":[1,"2",3.4,[5,6,[7,8]]],"objects":{"prop1":"hello test","prop2":[{"id":1,"name":"item1"},{"id":2,"name":"item2","teste":{"maisum":[1,2,3]}}]}}]
From the original poster: Typically, my situation may not generalize well, but because I found a very simple solution, I'll post it here in case it helps anybody else finding this.
First of all, for this particular api, the token and other argument were passed in the querystring and the method was GET, not POST. Thus the .send command had no argument. That's all it took to get the JSON string returned. Thus:
set objXMLhttp = Server.Createobject("MSXML2.ServerXMLHTTP")
objXMLhttp.open "GET","https://api.abc.com/argument1/?token=mysecret", false
objXMLhttp.setRequestHeader "Content-type","application/json"
objXMLhttp.setRequestHeader "Accept","application/json"
objXMLhttp.send
strResponse = objXMLhttp.responseText
By the way, if I HAD needed to send a JSON-formatted argument, as has been pointed out by others, often (for simple structures) it is easy to simply create this instead of using a 3rd-party library. (E.g., from a post on this site: {"Email":"asdf#hotmail.com", "firstname":"joe", "lastname":"smith"} ).
Finally, just as it is easy to create simple JSON strings, returned data, if simple, can easily be parsed. In my case, the return always had a brace at the beginning and end, then was a simple JSON comma-delimited list of colon-pairs. This was easily split into a vbscript array (remember, my post was for classic ASP) and parsed into a dictionary (ParseJSON) as follows (note I needed to strip off all the quotation marks):
strResponse = Left(strResponse,Len(strResponse)-1) ' remove right-brace
strResponse = Right(strResponse,Len(strResponse)-1)
Dim ParseJSON
Set ParseJSON = CreateObject("Scripting.Dictionary")
ParseJSON.CompareMode = vbTextCompare
ArryJSON = Split(strResponse,",")
' parse into a dictionary
For Each jPair In ArryJSON
' take jPair apart and insert into dictionary
onePair = Split(jPair,":")
aa = onePair(0)
aa = Left(aa,Len(aa) - 1) ' remove quotation mark
aa = Right(aa,Len(aa) - 1)
bb = onePair(1)
bb = Left(bb,Len(bb) - 1)
bb = Right(bb,Len(bb) - 1)
ParseJSON.Add aa,bb
Next
I am using Classic ASP and ASPJSON (http://www.aspjson.com/) to try to extract data returned in JSON format when sending an email via the SendGrid API.
This is some sample JSON data:
{
"message":"error",
"errors":[
"some errors"
]
}
I can access the values of the "message" section via:
Set oJSON = New aspJSON
oJSON.loadJSON(string_containing_json)
json_status = ap(oJSON.data("message"))
response.write(json_status)
However, I can't access the values of the "errors" section as it's sort of one level down.
Is it possible to get at that?
The errors are stored as a Dictionary object. You can enumerate them like this:
dim errors : set errors = oJSON.data("errors")
dim curError
for curError = 0 to errors.Count -1
Response.Write( errors(curError))
Response.Write( "<br />")
next
I am trying to return a JSON object from an aspx page using Jayrock.JSON.
My code for writing it out is this:
using (JsonTextWriter writer = new JsonTextWriter(Response.Output))
{
writer.WriteStartObject();
for (int i = 0; i < rdr.FieldCount; i++)
{
writer.WriteMember(rdr.GetName(i).ToString());
writer.WriteString(rdr[i].ToString());
}
writer.WriteEndObject();
}
This is inside of an rdr.Read() loop.
The outputted JSON looks like this: (though I added the line breaks manually)
{
"BugID":"1087",
"AddedBy":"",
"BugDate":"5/2/2010 9:45:34 AM",
"BugTitle":"/admin/ajax_thirdpartylog.asp",
"Classify":""
,"ErrPage":"/admin/ajax_thirdpartylog.asp",
"StoreID":"71",
"UserID":"15438",
"ErrDesc":"Type mismatch: 'formatnumber'",
"ErrDump":"*** VARIABLES DUMP ***\r\n\r\n*** Form Variables ***\r\n\r\ncalmonth : 8\r\ncalmonth2 : 8\r\nfromdate : 8/1/2009\r\ncalyear : 2009\r\ntodate : 8/31/2009\r\ncalyear2 : 2009\r\nr : 978402\r\nthirdtype : 1\r\nButton : Generate Third Party Log\r\n\r\n*** Query String Variables ***\r\n\r\n\r\n\r\n*** REPORT END ***\r\n",
"ErrLine":"74",
"DateFixed":"",
"Counter":"16",
"AssignTo":""
}
{
"BugID":"1086",
"AddedBy":"",
"BugDate":"5/1/2010 11:58:54 PM",
"BugTitle":"/admin/Charts/monthsales_s.asp",
"Classify":"",
"ErrPage":"/admin/Charts/monthsales_s.asp",
"StoreID":"402",
"UserID":"141928",
"ErrDesc":"Script timed out",
"ErrDump":"*** VARIABLES DUMP ***\r\n\r\n*** Form Variables ***\r\n\r\n\r\n*** Query String Variables ***\r\n\r\nmonth1 : 9/1/2009\r\nr : 75333803\r\n\r\n\r\n*** REPORT END ***\r\n",
"ErrLine":"0",
"DateFixed":"",
"Counter":"",
"AssignTo":""
}
I'm not really sure what I'm doing wrong, but on my page reading this JSON, when I try to do .evalJSON (using prototypejs) I get errors saying that the JSON is malformed.
Can anyone advise me what to change?
This:
"AssignTo":""
}
{
is the invalid JSON. You can a string to see if it's valid JSON at JSON Lint. I'm not sure what this should be like, but an empty object would be like this (don't need "", brackets reversed, missing comma):
"AssignTo":
{
},
The problem is that you are writing multiple JSON objects whereas what you are probably trying to do is produce a JSON array of JSON objects. Given your code snippet, I'm assuming rdr holds some IDataReader implementation like SqlDataReader. If that's true then you need to modify your code to start and end a JSON array around the outer read loop, as follows:
using (JsonTextWriter writer = new JsonTextWriter(Response.Output))
{
writer.WriteStartArray();
while (rdr.Read())
{
writer.WriteStartObject();
for (int i = 0; i < rdr.FieldCount; i++)
{
writer.WriteMember(rdr.GetName(i).ToString());
writer.WriteString(rdr[i].ToString());
}
writer.WriteEndObject();
}
writer.WriteEndArray();
}
Jayrock will automatically delimit each JSON object value with a comma (,) when inside a JSON array so now the output should resemble the following and valid JSON:
[
{
"BugID":"1087",
"AddedBy":"",
"BugDate":"5/2/2010 9:45:34 AM",
"BugTitle":"/admin/ajax_thirdpartylog.asp",
"Classify":""
,"ErrPage":"/admin/ajax_thirdpartylog.asp",
"StoreID":"71",
"UserID":"15438",
"ErrDesc":"Type mismatch: 'formatnumber'",
"ErrDump":"*** VARIABLES DUMP ***\r\n\r\n*** Form Variables ***\r\n\r\ncalmonth : 8\r\ncalmonth2 : 8\r\nfromdate : 8/1/2009\r\ncalyear : 2009\r\ntodate : 8/31/2009\r\ncalyear2 : 2009\r\nr : 978402\r\nthirdtype : 1\r\nButton : Generate Third Party Log\r\n\r\n*** Query String Variables ***\r\n\r\n\r\n\r\n*** REPORT END ***\r\n",
"ErrLine":"74",
"DateFixed":"",
"Counter":"16",
"AssignTo":""
},
{
"BugID":"1086",
"AddedBy":"",
"BugDate":"5/1/2010 11:58:54 PM",
"BugTitle":"/admin/Charts/monthsales_s.asp",
"Classify":"",
"ErrPage":"/admin/Charts/monthsales_s.asp",
"StoreID":"402",
"UserID":"141928",
"ErrDesc":"Script timed out",
"ErrDump":"*** VARIABLES DUMP ***\r\n\r\n*** Form Variables ***\r\n\r\n\r\n*** Query String Variables ***\r\n\r\nmonth1 : 9/1/2009\r\nr : 75333803\r\n\r\n\r\n*** REPORT END ***\r\n",
"ErrLine":"0",
"DateFixed":"",
"Counter":"",
"AssignTo":""
}
]