HttpWebRequest: How to dynamically store variable in JSON array format - json

I have my HttpWebRequest body that needs to be in JSON array format and I have to populate it dynamically at run time.
Dim body As String = "{""studentForm"":[{""title"":""Law Major"",""description"":""Excellent Student. Work hard. Very Intelligent, and so on..."",""phone"":""0123456789"",""categoryId"":1197,""categoryName"":""Senior Student"",""parentCategory"":9,""location"":{""latitude"":45.151053,""longitude"":-79.398193,""radius"":1000},""categoryAttributes"":[],""imageUrls"":[]}]}"
So I need to have variables like varTitle, varDescript, varDescript, and so on into the JSON array. I tried to do that the below way but doesn't work.
Dim body As String = "{""studentForm"":[{""title"":varTitle,""description"":varDescript,""phone"":varDescript,""categoryId"":1197,""categoryName"":""Senior Student"",""parentCategory"":9,""location"":{""latitude"":45.151053,""longitude"":-79.398193,""radius"":1000},""categoryAttributes"":[],""imageUrls"":[]}]}"
I read about Deserialization / Serialization from a couple of websites but still can't achieve what I'm looking for.

Related

Newtonsoft.Json.JsonSerializationException - Cannot deserialize the current JSON object

Lot of similar questions but still not able to make it. Here is my
code in vb.net and this is the json response. enter image description here I know this is because of [] but i'm using list don't know still getting the same error.
This is because you are receiving a JSON array and not a single JSON object.
You need to deserialize the array like this -
Dim Items_Array = Newtonsoft.Json.JsonConvert.DeserializeObject(Of T())(jsonString)

Converting a string of an array into an array in JS

I have a project I'm working on that implements MySQL, React and Express.js. I need to save an array into MySQL, but there are currently no ways to save an array, as far as I could see, so I was forced to convert it into a string. When I get it back from Express to the client, it's obviously a string, so I can't access the data. This array is used for a graph, mainly. What are some of the ways I can convert this string back to an array?
You can use JSON.parse() to convert a string into an array.
const response = "[1,2,3]";
console.log(JSON.parse(response));
You can store your json object (including arrays )in form of text in mysql database.What you have to do is JSON.stringify("your array") and persist it in database.And while you are retrieving it back from database you can JSON.parse() to get it in form of JavaScript object
Depends on how you formed the string. If you used , for joining the elements, then you can use javascript's string.split() method.
let str = '1,2,3,4';
let arr = str.split(',');
Just pass in whatever delimiter you used to join the elements.
OR
If you're saving elements as a json string, then use JSON.parse(str) as shown by Nils Kähler in his answer

POST JSON string from Form in VB.NET

Here is my situation:
I have a form that is collecting a list of items in a textarea as a JSON Object.
The form textarea looks like this:
<textarea id="listItems">
[
{"id":"1","name":"apple"},
{"id":"2","name":"orange"},
{"id":"3","name":"banana"}
]
</textarea>
I need to be able to parse that string and POST each item into a SQL Table.
ItemID | ItemName
-----------------
1 | apple
2 | orange
3 | banana
I don't think I have a good understanding of using the JavaScriptSerializer Class. I'm using VB.net
I don't have any server-side code yet but I know that I have to parse out the JSON string and then loop through it and then save each item.
Couldn't I just convert the JSON string into a DataTable and then loop through that temporary table?
Not sure. I'm trying to figure this out but some help would be useful.
Also I'm referencing a few SO posts to see if maybe I can figure this out
This one
This one
So expecting the following Json Object at the Server
[
{"id":"1","name":"apple"},
{"id":"2","name":"orange"},
{"id":"3","name":"banana"}
]
you would be able to do this:
Public Function DoSomething()
Dim jsonObject = "[{""id"":""1"",""name"":""apple""},{""id"":""2"",""name"":""orange""},{""id"":""3"",""name"":""banana""}]"
Dim obj = New JavaScriptSerializer().Deserialize(Of TestObject())(jsonObject)
End Function
With this Model
Public Class TestObject
Public Property id As Integer
Public Property name As String
End Class
At runtime you will have an array of Objects in obj which you can then manipulate and fill into a DataTable or directly feed to the Database. Converting the Json into an Object is not the only option you have here but it is a convenient one.
Since you did not specify the context you are working in it is a little unclear what might be the best solution to your case. Maybe you want to do a little research on different Json Frameworks (for example Json.net) as well as Data-Handling with Databases so you get ideas about the how and when.
This was the best answer I found and I adjusted it to meet my needs.
I've also included the link to the duplicate POST that answered my question.
I'm also referencing another similar post which has a similar situation.
This is the link to the .Net Fiddle that demonstrates what I was looking for.
DEMO
How to deserialize JSON which can be an array or a single object
How to handle both a single item and an array for the same property using JSON.net

VBA getting values from a collection?

I am very new to VBA and I can not figure out how to get values from a Collection.
This is my code:
Dim p As Object
Set p = JSON.parse(Response.Content)
Dim links As Object
Set links = p.Item("links")
In the debugger for "links" I see:
I am using this library to parse json : http://www.ediy.co.nz/vbjson-json-parser-library-in-vb6-xidc55680.html
The part I have in json is:
"links":[
{
"rel":"next",
"href":"www.google.com"
}
]
How can I get the value of "rel" here?
Don't forget the bang operator, designed for collection access by key:
links(1)!rel
or:
links(1)![rel] 'When there are spaces or reserved words.
I will answer my own question:
links(1).Item("rel")
worked...
Regards..
Using JavaScript features of parsing JSON, on top of ScriptControl, we can create a parser in VBA which will list each and every data point inside the JSON. No matter how nested or complex the data structure is, as long as we provide a valid JSON, this parser will return a complete tree structure.
JavaScript’s Eval, getKeys and getProperty methods provide building blocks for validating and reading JSON.
Coupled with a recursive function in VBA we can iterate through all the keys (up to nth level) in a JSON string. Then using a Tree control (used in this article) or a dictionary or even on a simple worksheet, we can arrange the JSON data as required.
You can see the full VBA code here

Use ScriptControl to parse JSON in VBA: transform result to dictionaries and collections

I would like to use Microsoft ScriptControl to parse a JSON string in VBA, and then transform the resulting Object into Dictionary and Collection objects. I already know how to do the parsing with ScriptControl, but cannot figure out how to map the result into the Dictionary and Collection classes. I'm guessing that if I could figure out how to loop through the properties of an Object this would become clear...
Dim sc As ScriptControl
Dim obj As Variant
Set sc = CreateObject("ScriptControl")
sc.Language = "JScript"
Set obj = sc.Eval("("+json+")") ' json is a string containing raw JSON
' Now what?
By the way, I've used the vba-json library to get the output in terms of Dictionaries and Collections, but I find this library somewhat slow. It does not use ScriptControl.
EDIT: I found a discussion of getting object properties in this post.
Using JavaScript features of parsing JSON, on top of ScriptControl, we can create a parser in VBA which will list each and every data point inside the JSON. No matter how nested or complex the data structure is, as long as we provide a valid JSON, this parser will return a complete tree structure.
JavaScript’s Eval, getKeys and getProperty methods provide building blocks for validating and reading JSON.
Coupled with a recursive function in VBA we can iterate through all the keys (up to nth level) in a JSON string. Then using a Tree control (used in this article) or a dictionary or even on a simple worksheet, we can arrange the JSON data as required.
VBA Code:http://ashuvba.blogspot.in/2014/09/json-parser-in-vba-browsing-through-net.html
loop
This will help you to loop - add a myitem(n) method in javascript
from there you can map through VB code.