Extract title in nested JSONObject cpprest/casablanca - json

I have a json file like this:
{
"company1":
{
"id": "123456",
"created": "2019"
},
"company2":
{
"id": "223424",
"created": "2020"
}
}
I'm using cpprest library for handle json data and REST API.
for accessing the id and created field in above json we can easily do this:
jsonObject[U("company1")].at(U("created")).as_string()
But how i can find company name, if i don't have them or how i can get created and id value without knowing company names?
I didn't find it on their wiki also.

It was straightforward!
For finding Company name iterate over JsonObject and then key value is the company names. Source
const json::value& v = previousTask.get();
for (auto iter = v.as_object.cbegin(); iter != v.as_object.cend(); ++iter)
{
const json::value &key = iter->first;
}

Related

How to access nested elements in json in flutter?

This is the json data structure used in flutter
flutter: {
"members": [
{
"firstName": "Michael"
},
{
"firstName": "Jennifer"
},
{
"firstName": "Lisa"
}
]
}
To access the above data I used the below code
var parsedData = json.decode(state.successResponse);
var name = parsedData['members'];
I am not able to access the inner field of firstName in the above json.
How should I do that?
Since members is JSON Array you can convert it to dart List type and then you can operate on the list (adding, removing, accessing elements by index).
You can do something like this -
List members = parsedData['members'];
//You can access members by index
print(members[1]); //prints {firstName: Jennifer}
print(members[1]['firstName']); //prints Jennifer
//Or you can iterate over the list
members.forEach((member){
print(member['firstName']);
});
Hope this helps!

Gatling JSON Feeder Unique POST Bodies

I have a JSON file that contains a JSON Array
test.json
[
{ "Name": "Bob" },
{ "Age": "37" },
{ "DOB": "12/01/1985"}
]
I would like to test each respective element in the JSON array against an endpoint to observe the performance of the system against unique payloads
currently I have
testService.scala
val payload = jsonFile("test.json").circular
val httpProtocol = http
.baseURL("http://test.com")
.headers(Map("Content-Type" -> "application/json"))
val scn = scenario("Test Service")
.feed(payload)
.exec(http("test_request")
.post("/v1/test")
.queryParam("key", "123")
.body()
I am not able to pass each respective child from the payload in the .body() as a JSON
The Gatling Docs say that the JSON Feeder loads the each element of the Array into a record collection
https://gatling.io/docs/2.3/session/feeder/
i.e:
record1: Map("id" -> 19434, "foo" -> 1)
record2: Map("id" -> 19435, "foo" -> 2)
and set the body to .body(StringBody("""[{"id": ${id}}]"""))
The issue is I have different keys (Name,Age,DOB) and I'd like each one to be a different request sent.
.body(StringBody("""[{"KEY_NAME_HERE": ${KEY_NAME_HERE}}]"""))
How do I achieve this?
This is how i am doing:-
company_users.json.json
[
{
"env":"dev",
"userName": "a#test.com",
"password": "Qwerty!12345678"
},
{
"env":"sit",
"userName": "b#test.com",
"password": "Qwerty!12345678"
},
{
"env":"uat",
"userName": "c#test.com",
"password": "Qwerty!12345678"
},
{
"env":"prod",
"userName": "d#test.com",
"password": "Qwerty!12345678"
}
]
Working Code Snippet:
val jsonFileFeederCompany = jsonFile("data/company_users.json").circular
val get_company_user_token = http("Get Company Tokens")
.post(gwt_token_url)
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.body(StringBody(
"""{
"env": "${env}",
"userName": "${userName}",
"password": "${password}"
}"""
)).asJson
.check(status.is(200))
.check(jsonPath("$.jwtToken").saveAs("jwtToken"))
val getCompanyUsersGwtToken = scenario("Create Company GWT token Scenario")
.feed(GetTokenRequest.jsonFileFeederCompany)
.exec(GetTokenRequest.get_company_user_token).exitHereIfFailed
This will read each array[position] from json and replace the values in request, to fetch security tokens from different env.
Hope this helps.
Regards,
Vikram Pathania
In your case JSONs from that array are loaded one by one, and since each first level key from that JSON will be saved as session attribute then users in your simulation end up with just 1 of 3 attributes depending which JSON was used. This way you can't (or to be precise can't easily) build body string. In that simple case it would be better to have JSONs with same fields, so you can rely on them when building request payload. Fe. you can place payload key and value in separate fields:
[
{
"key":"Name",
"value":"Bob"
},
{
"key":"Age",
"value":"37"
},
{
"key":"DOB",
"value":"12/01/1985"
},
]
This way for each user in simulation you will have two attributes key and value so you will be able to construct payload like:
.body(StringBody("""{"${key}": "${value}"}"""))
Of course this will work only in that simple case you described and with string-only values in JSONs. If your final goal is to make something more complex please provide real-life example.

Process a list of map to get a value of a key in the map

I have a list of map (parsed from json output of a rest request) like
[[Mobile:9876543210, Name:ABCD], [Mobile:8765432109, Name:EFGH], [Mobile:7654321098, Name:IJKL], [Mobile:6543210987, Name:MNOP]]
Original JSON was like
{
"data": [{
"Name": "ABCD",
"Mobile": "9876543210"
},
{
"Name": "EFGH",
"Mobile": "8765432109"
},
{
"Name": "IJKL",
"Mobile": "7654321098"
},
{
"Name": "MNOP",
"Mobile": "6543210987"
}
]
}
I want to get the mobile value from the name
Tried some things but just not working out.
Trying this in JMETER JSR223 post processor using Groovy.
You should be able to get the Mobile based on Name.
Below code fetches the Mobile 8765432109 when Name is EFGH from the OP's data. Similarly you can change the value of Name to get the right Mibile.
//Pass jsonString value to below parseText method
def json = new groovy.json.JsonSlurper().parseText(jsonString)
def result = json.data.find { it.Name == 'EFGH' }.Mobile
println result
You can quickly try online Demo
Here is an example Groovy code to fetch Name:Mobile pairs from the original JSON response (use the code in the JSR223 PostProcessor)
def json = new groovy.json.JsonSlurper().parse(prev.getResponseData())
json.data.each {entry ->
entry.each {k, v -> log.info("${k}:${v}")}
}
Demo:
References:
Groovy: Parsing and producing JSON
Groovy Is the New Black

Dynamically build json using groovy

I am trying to dynamically build some json based on data I retrieve from a database. Up until the opening '[' is the "root" I guess you could say. The next parts with name and value are dynamic and will be based on the number of results I get from the db. I query the db and then the idea was to iterate through the result adding to the json. Can I use jsonBuilder for the root section and then loop with jsonSlurper to add each additional section? Most of the examples I have seen deal with a root and then a one time "slurp" and then joining the two so wasn't sure if I should try a different method for looping and appending multiple sections.
Any tips would be greatly appreciated. Thanks.
{
"hostname": "$hostname",
"path": "$path",
"extPath": "$extPath",
"appName": "$appName",
"update": {"parameter": [
{
"name": "$name",
"value": "$value"
},
{
"name": "$name",
"value": "$value"
}
]}
}
EDIT: So what I ended up doing was just using StringBuilder to create the initial block and then append the subsequent sections. Maybe not the most graceful way to do it, but it works!
//Create the json string
StringBuilder json = new StringBuilder("""{
"hostname": "$hostname",
"path": "$path",
"extPath": "$extPath",
"appName": "$appName",
"update": {"parameter": ["""
)
//Append
sql.eachRow("""<query>""",
{ params ->
json.append("""{ "name": "params.name", "value": "params.value" },""");
}
)
//Add closing json tags
json.append("""]}}""")
If I got your explanation correctly and if the data is not very big (it can live in memory), I'd build a Map object (which is very easy to work with in groovy) and convert it to JSON afterwards. Something like this:
def data = [
hostname: hostname,
path: path,
extPath: extPath,
appName: appName,
update: [parameter: []]
]
sql.eachRow(sqlStr) { row ->
data.update.parameter << [name: row.name, value: row.value]
}
println JsonOutput.toJson(data)
If you're using Grails and Groovy you can utilize grails.converters.JSON.
First, define a JSON named config:
JSON.createNamedConfig('person') {
it.registerObjectMarshaller(Person) {
Person person ->
def output = [:]
output['name'] = person.name
output['address'] = person.address
output['age'] = person.age
output
}
}
This will result in a statically defined named configuration for the Object type of person. Now, you can simply call:
JSON.use('person') {
Person.findAll() as JSON
}
This will return every person in the database with their name, address and age all in one JSON request. I don't know if you're using grails as well in this situation though, for pure Groovy go with another answer here.

Getting the name of each field in JSON

I'm trying to parse a random JSON file in Grails.
First I need to get the name of each field
For example, given below JSON file,
{
"abbreviation": "EX",
"guid": "1209812-1l2kj1j-fwefoj9283jf-ae",
"metadata": {
"dataOrigin": "Example"
},
"rooms":
[
],
"site": {
"guid": "1209812-1l2kj1j-fwefoj9283jf-ae"
},
"title": "Example!!"
}
I want to find out the structure of the JSON file(lists of keys maybe), for example I want to save the list of keys such as 'abbreviation', 'guid', 'metadata', 'rooms', 'site', 'title' from this JSON file.
How would I do this?
(We need the name of the keys in order to get the value of that key, so with a arbitrarily structured JSON file I need to find out the keys first)
You can try below code
def filePath = "JSONFILE.json"
def text = new File(filePath).getText()
def json = JSON.parse(text)
def jsonKeys = json.collect{it.key}
println(jsonKeys)
This will print all json keys
From what dmahaptro commented, I figured out how to get all the keys within a JSON object.
Here is a simple sample code I wrote to test it
String jsonFile = new JsonSlurper().parseText(new URL(path to the json file).text)
JSONArray jsonParse = new JSONArray(jsonFile)
int len = jsonParse.length()
def names = []
def keys = []
(0..len-1).each {
JSONObject val = jsonParse.getJSONObject(it)
int numKeys = val.length()
names = val.names()
keys = val.keySet()
(0..numKeys-1).each {
def field = names[it]
println field +" : " + val."${field}"
}
}
This will print the key:value pair given a JSON file.