JsonConverter Excel VBA multiple results - json

A small question: i'm using JsonConverter from Github.
(https://github.com/VBA-tools/VBA-JSON/blob/master/JsonConverter.bas)
Code is working on most of the "GET" request.
Only when the same 'column' is accuring multiple times in the 'ResponseText' then it's not. (like "imei" in the example)
So I need a way to handle a long 'Responsetext' to fill multiple rows in an access db.
Dim Json As Object
Set Json = JsonConverter.ParseJson(xmlhttp.ResponseText)
MsgBox (Json("imei")) 'temp
Error 5: Invalid Procedure or Call Argument.
Any ideas?
Many thanks,

I can only provide a part of the answer, because I cannot recreate it, without the full JSON Response Text:
The response with mutliple values in JSON returns an Object of the type Collection. Hence you have to use a loop to iterate through all responses. Like this:
Dim Json As Object
Set Json = JsonConverter.ParseJson(xmlhttp.ResponseText)
For Each singleJsonItem In Json
'What object type is singleJsonItem? To find out, maybe use:
'MsgBox singleJsonItem("imei")
Next singleJsonItem
You have to find out the object type of the collectionentries to extract the JSON Entry.

Solved like this:
used : https://github.com/VBA-tools/VBA-JSON
and named the module: 'mdl_JsonConverter'
Set Json = mdl_JsonConverter.ParseJson(xmlhttp.ResponseText)
For Each item In Json
input_1 = item("input_1")
input_2 = item("input_2")
'THEN DO SOMETHING WITH VALUES F.E. ADDING THEM IN A TABLE
Next

If you responseText contains a searchRecords list then filter by searchRecords before for each
Set Json = JsonConverter.ParseJson(strResponse)
For Each singleJsonItem In Json("searchRecords")
'What object type is singleJsonItem? To find out, maybe use:
Msgbox singleJsonItem("Name")
Next singleJsonItem

Related

Output array to excel with VBA

Im am trying to output an array coming from JsonConverter to excel but I get an error 1004:
Sub test()
Dim parsed As Object
Dim myArray As Variant
Set parsed = JsonConverter.ParseJson("{""a"":123,""b"":[1,2,3,4],""c"":{""d"":456}}")
Set myArray = parsed("b")
Set TxtRng = ThisWorkbook.Sheets("Project").Range("A44:D44")
TxtRng.Value = Application.Transpose(myArray)
End Sub
The error is at TxtRng.Value = Application.Transpose(myArray).
Can someone help solve this issue? Thank you.
First: You shouldn't assume that it is commonly known what JsonConverter because it is not a build-in object. I assume you are talking about https://github.com/VBA-tools/VBA-JSON ?
In your example, parsed will return a Dictionary and parsed("b") will return a Collection. Application.Transpose expects a (2-dimensional) array as parameter, but will not work with a collection.
Probably the easiest way to solve this is simply to loop over the collection. Or use a helper function like similar to Converting VBA Collection to Array to create an intermediate array first

add data to a datatable from JSON string - vb.net

I need to know how to populate datatable from JSON string in vb.net code.
the JSON string
{"success":true,"message":"","result":[{"Paper1:null,"StateId":"57ee","School":"1A","Received":"2018-07-03T08:10:05.22","TimeS":"00","STAT":"98","ScoreCard":"76"},{"Paper1:null,"StateId":"52ef","School":"1A","Received":"2018-07-03T08:10:05.22","TimeS":"00","STAT":"88","ScoreCard":"57"}]}
I need to know how to populate above string to a datatable
The above string is in a WebResponse. So is there any way to read the webresponse (here I have used a streamreader, or any other good method) and populate to a datatable?
my code which I got above string.
Dim rqst As WebRequest = WebRequest.Create(uri_variable)
Dim res_p As WebResponse
rqst.Method = "GET"
rqst.Headers.Add("apisign:" & sign)
res_p = rqst.GetResponse()
Dim reader As New StreamReader(res_p.GetResponseStream())
Dim JSON_String as string = reader
P.S: EDIT: I included a screenshot for the user "CruleD"
https://i.stack.imgur.com/EYbP0.png
Heh, this again.
Imports System.Web.Script.Serialization ' for reading of JSON (+add the reference to System.Web.Extensions library)
Dim JSONC = New JavaScriptSerializer().DeserializeObject(JSON_String)
Inspect JSONC with breakpoint. You will see how it looks then you decide what you want to do with it.
Comparing files not working as intended
Similar answer I gave in another thread.
Edit:
JSONC("result")(0)("Quantity")
First you get the contents of "result", then you select which collection you want, in this case first (so 0) then you search for whatever key you want again eg "Quantity" like you did for result originally.
There are other ways to do the same thing, but this one should be pretty straight forward.
There are 3 types of deserialization, check them out if you want.

How to print an object as JSON to console in Angular2?

I'm using a service to load my form data into an array in my angular2 app.
The data is stored like this:
arr = []
arr.push({title:name})
When I do a console.log(arr), it is shown as Object. What I need is to see it
as [ { 'title':name } ]. How can I achieve that?
you may use below,
JSON.stringify({ data: arr}, null, 4);
this will nicely format your data with indentation.
To print out readable information. You can use console.table() which is much easier to read than JSON:
console.table(data);
This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.
It logs data as a table. Each element in the array (or enumerable property if data is an object) will be a row in the table
Example:
first convert your JSON string to Object using .parse() method and then you can print it in console using console.table('parsed sring goes here').
e.g.
const data = JSON.parse(jsonString);
console.table(data);
Please try using the JSON Pipe operator in the HTML file. As the JSON info was needed only for debugging purposes, this method was suitable for me. Sample given below:
<p>{{arr | json}}</p>
You could log each element of the array separately
arr.forEach(function(e){console.log(e)});
Since your array has just one element, this is the same as logging {'title':name}
you can print any object
console.log(this.anyObject);
when you write
console.log('any object' + this.anyObject);
this will print
any object [object Object]

U-SQL Json Extractor is only pulling one record

I'm testing data lake for an application I am developing. I'm new to U-SQL and data lake and am just trying to query all records in a JSON file. Right now, It's only returning one record and I'm not sure why because the file has about 200.
My code is:
DECLARE #input string = #"/MSEStream/output/2016/08/12_0_fc829ede3c1d4cf9a3278d43e7e4e9d0.json";
REFERENCE ASSEMBLY [Newtonsoft.Json];
REFERENCE ASSEMBLY [Microsoft.Analytics.Samples.Formats];
#allposts =
EXTRACT
id string
FROM #input
USING new Microsoft.Analytics.Samples.Formats.Json.JsonExtractor();
#result =
SELECT *
FROM #allposts;
OUTPUT #result
TO "/ProcessedQueries/all_posts.csv"
USING Outputters.Csv();
Data Example:
{
"id":"398507",
"contenttype":"POST",
"posttype":"post",
"uri":"http://twitter.com/etc",
"title":null,
"profile":{
"#class":"PublisherV2_0",
"name":"Company",
"id":"2163171",
"profileIcon":"https://pbs.twimg.com/image",
"profileLocation":{
"#class":"DocumentLocation",
"locality":"Toronto",
"adminDistrict":"ON",
"countryRegion":"Canada",
"coordinates":{
"latitude":43.7217,
"longitude":-31.432},
"quadKey":"000000000000000"},
"displayName":"Name",
"externalId":"00000000000"},
"source":{
"name":"blogs",
"id":"18",
"param":"Twitter"},
"content":{
"text":"Description of post"},
"language":{
"name":"English",
"code":"en"},
"abstracttext":"More Text and links",
"score":{}
}
}
Thank you for the help in advance
The JsonExtractor takes an argument that allows you to specify which items or objects are being mapped into rows using a JSON Path expression. If you don’t specify anything it will take the top root (which is one row).
You want every one of the items in the array, so you specify it as:
USING new Microsoft.Analytics.Samples.Formats.Json.JsonExtractor("[*]");
Where [*] is the JSON Path expression that says give me all the elements of the array which in this case is the top-level array.
If you have a JSON node in your field called id, your original script posted in the question would return the node with name "id" under the rootnode. To get all the nodes, your script will be structured as
#allposts =
EXTRACT
id string,
contenttype string,
posttype string,
uri string,
title string,
profile string
FROM #input
USING new Microsoft.Analytics.Samples.Formats.Json.JsonExtractor();
Please let us know if it works. The alternative would be to extract it using a native extractor to read it all in a string (as MRys mentioned, as long as your JSON is under 128 KB this would work).
#allposts =
EXTRACT
json string
FROM #input
USING Extractors.Text(delimiter:'\b', quoting:false);

Trying to get a simple loop of JSON passed to POST - Python

I have a WS using Flask/python 2.7. I have 1 JSON object passed to the WS. I have been successful in capturing the object and returning the whole JSON.
I have looked all over for examples (many use print of test dataset in python) and have tried json.dumps, json.loads, json.dump, json.load, for loops, etc.
What I would like to do seems simple and I know it is me, but I get errors no matter what I try. I am trying to parse the JSON, put the values in to variables, and do "stuff".
This works:
#app.route('/v1/test', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'application/json':
return "JSON Message: " + json.dumps(request.json, separators=(',',':'))
else:
return "415 Unsupported Media Type"
This does not (and many variations of this using different things):
jsonobject = json.dumps(request.json)
pstring = json.loads(jsonobject)
for key, value in pstring.iteritems():
return value
What I want to do (pseudo code):
for each JSON
get the name value pairs in to a place where I can do something like this (which was done on a flat file)
input_data = pd.read_csv(sio, delimiter=',', names=columns)
probs = model.predict_proba(input_data)
I am sure I didn't make this as clear as I could but it is a challenge because I get errors like below (examples -- not all at once of course) with all the different things I try:
AttributeError: 'dict' object has no attribute 'translate'
TypeError: 'dict' object is not callable
AttributeError: 'str' object has no attribute 'iteritems'
So after all that, what is the right way to do this?