vb.net - Loop throught JSON and get all data - json

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)

Related

How to select the same property in a json array? ASP.NET Core

I have this string:
{
"timezone":"UTC",
"serverTime":1669313639361,
"symbols":[
{
"symbol":"ETHBTC",
"status":"TRADING",
"baseAsset":"ETH",
},
{
"symbol":"LTCBTC",
"status":"TRADING",
"baseAsset":"LTC",
}
]
I want to transform it into a json with only symbol properties like:
["ETHBTC", "LTCBTC"]
You can parse your json and use LINQ
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
string[] symbols = JObject.Parse(json)["symbols"].Select(x => (string) x["symbol"]).ToArray();
UPDATE
if you want a json array
JArray symbolsArr = new JArray( JObject.Parse(json)["symbols"].Select(x => (string) x["symbol"]));
//or
json = symbolsArr.ToString();
//or
json= JsonConvert.SerializeObject(symbols);
By you don't need to convert a string array to json if you want to use it in API, you can just return an array, it will be automatically converted to json my MVC controller action

How to pass multiple json objects of array to post request in jmeter using groovy script

POST API is triggering fine and taking only first json object from array and rest of the json objects are not passing. I need to trigger API with multiple json payloads sequentially using JMeter and Groovy.
json payload : Below is the sample json payload
[
{
"person": "abc",
"Id": "123"},
{
"person": "adfg",
"Id": "12883"},
{
"person": "adf",
"Id": "125"}
]
Groovy code : Reading data from json file which includes multiple json objects and send it to post request in jmeter.
try
{
JsonSlurper jsonSlurper=new JsonSlurper();
def jsonPayload = jsonSlurper.parse(new File('PAYLOAD.json'))
String inputData = new groovy.json.JsonBuilder(jsonPayload)
JsonElement root = new JsonParser().parse(inputData);
JsonArray jsonArray = root.getAsJsonArray();
log.info("jsonArray:"+jsonArray);
if(jsonArray != null && !jsonArray.isEmpty())
{
jsonArray.each{paylodData ->
println paylodData
log.info("post data:"+paylodData);
vars.putObject("payloads", paylodData.toString())
log.info('Generated body: ' + vars.getObject('payloads'))
}
}
}catch (FileNotFoundException fe) {
log.info("Error: Please Check the file path");
}
JMeter Test : Triggering same API with multiple payloads
using below variable in post request body
${payloads}
NOTE : API is triggering fine and taking only first json object and rest of the json objects are not passing. I need to trigger API with multiple json payloads sequentially.
What are you trying to achieve?
You have a foreach loop which iterates the JSON Array and writes the inner object value into a payloads JMeter Variable
The point is that each iteration of the foreach loop overwrites the previous value in the variable so you will always get the last value.
You either need to replace jsonArray.each with jsonArray.eachWithIndex and store each array member into a separate variable like:
payload_0 = first array member
payload_1 = second array member
etc.
or transform the response into another format, but here I cannot suggest anything because I don't know what is the expected one.
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy: What Is Groovy Used For?

How to replace a JSON value stored in a JSON file and use that in a Rest Assured test

I have a set of input data files in JSON and I am trying to replace a value present in a JSON file and use that value to do a post request in restAssured
The JSON file has
{
"items": [
{
"item_ref": 241,
"price": 100
}
]
}
jsonbody below is a String of the above JSON file
This is the code that fails:
JSONObject jObject = new JSONObject(jsonbody);
jObject.remove("item_ref");
jObject.put("item_ref","251");
System.out.println(jObject);
This is what I am getting:
{"item_ref":"251","items":[{"item_ref":241,"price":100}]}
What I want is {"items":[{"item_ref":251,"price":100}]}
I also tried
JSONObject jObject = new JSONObject(jsonbody);
jObject.getJSONObject("items").remove("item_ref");
jObject.getJSONObject("items").put("item_ref","251");
System
But it says JSONObject["items"] is not a JSONObject.
All I need is to replace the 241 with 251. Is there an easier way to do this?
In general if we have a predefined JSON body file and if we want to replace some of the values in the body and use that in our POST calls within RestAssured, is there any easier way to do it?
The problem is - field item_ref and price are not in JSON Object as you think they are.
They are in JSON Array which contains JSON Objects. In order to modify that value, you have to get elements of the array and THEN execute very similar code you wrote.
Check this out:
JSONObject jObject = new JSONObject(jsonbody);
JSONArray array = jObject.getJSONArray("items");
JSONObject itemObject = (JSONObject) array.get(0); //here we get first JSON Object in the JSON Array
itemObject.remove("item_ref");
itemObject.put("item_ref", 251);
The output is:
{"items":[{"item_ref":251,"price":100}]}
Also, you can create a Hashmap:
HashMap<String,String> map = new HashMap<>();
map.put("key", "value");
RestAssured.baseURI = BASE_URL;
RequestSpecification request = RestAssured.given();
request.auth().preemptive().basic("Username", "Password").body(map).put("url");
System.out.println("The value of the field after change is: " + map.get("key"));

random selection from JSON

I try to convert some JSON string data from JSON object into an array.
When I loop over the JSON is it assign the JSON strings into diffrent array cells, eventually I get all the strings from the JSON but in diffrent order in the array each time I run the program.
for (var i:String in data)
{
// get panel tabs and players for each tab
for (var f:String in data[i].tabs)
{
tabsNames.push(f);
}
}
sometimes tabsNames = [ 1,2,3]
sometimes tabsNames = [ 2,3,1] etc'
I cant use sort because I cant know the type of the information that I will get from the JSON.
A JSON object is an unordered set of name/value pairs:
"obj" : {"propA" : "valueA", "propB":"valueB"}
A JSON array is an ordered collection of values:
"arr" : ["propA":"valueA", "propB":"valueB"]
If your data will be stored in JSON Object as list, you always get data in same order.

JSON String formed improperly using Jayrock in .NET

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