How to extract specific values from JSON response in Postman and concatenate - arrays

I need to be able to do the following in Postman
Parse through a JSON response
Retrieve specific values: some nested, some not
(optional) Concatenate the final result
I can currently perform 1 and I can accomplish 2 for one specific value with the help of this explanation link
What I can't do is retrieve two values. Below is the sample response I am working with
{
"part": "9FH74T00",
"summaries": [
{
"id": "A1AGQF32TR"
}
]
}
I was able to modify the JS from the link above to extract the nested id value
var response = JSON.parse(responseBody);
var ids = response.summaries.map(function(summary) {
return summary.id;
});
console.log(ids);
How can I expand on the JS to also retrieve the part value and ideally output that in the console as part = id or 9FH74T00 = A1AGQF32TR

#lucas-nguyen's seems a valid response/comment to what you propose. What is not well explained is the model. summaries is an array so would you get multiple ids? The fact that you use a map makes me thing there will be multiple ids.
part = id1,id2,id3
or
part = id1
part = id2
part = id3
I've created a sample request with your payload and two ids in summaries. I've console.log 3 approaches:
single part and single id
single part and ids in a list
single part and ids in tuples
So with the example response:
{
"part": "9FH74T00",
"summaries": [
{
"id": "A1AGQF32TR"
},
{
"id": "SECONDID"
}
]
}
You would get the following output:
Option 1:
9FH74T00 = A1AGQF32TR
Option 2, list of ids:
9FH74T00 = A1AGQF32TR,SECONDID
Option 3, list of ids:
9FH74T00 = A1AGQF32TR
9FH74T00 = SECONDID
If for some reason you can't open the example, this is my test tab:
const response = pm.response.json().data;
// Just concatenate single part and single id
console.log("\nOption 1:")
console.log(`${response.part} = ${response.summaries[0].id}`)
// Co
console.log("\nOption 2, list of ids:")
const ids = response.summaries.map( x => x.id)
console.log(`${response.part} = ${ids.join(",")}`)
console.log("\nOption 3, list of ids:")
ids.forEach( x => console.log(`${response.part} = ${x}`))

Related

How to extract data from an API and create an array to send to the another API in Jmeter?

Example:
API A:
{
"customer":[
{
"name":"Jane",
"phone":"9999999",
"email":"jane#test.com"
},
{
"name":"John",
"phone":"8888888",
"email":"john#test.com"
},
{
"name":"Joe",
"phone":"7777777",
"email":"Joe#test.com"
}
]
}
Using the JSON extractor, I want to get the names of all the customers
so: Jane, John, Joe
How do I get these values and turn them into an array
[{"name":"Jane", "name":"John", "name":"Joe"}]
And pass it onto the next API?
Note: That it has to be dynamic so API A could show different 2 names or 1 name or more and needs to be adjusted into the array
First of all your [{"name":"Jane", "name":"John", "name":"Joe"}] is not a valid JSON, you can check it yourself:
so I strongly doubt that this is the string you need to generate.
So if you really need to construct this value you can do something like:
Add JSR223 PostProcessor as a child of the request which returns this "customers" data
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def payload = new StringBuilder()
payload.append('[{')
0.upto(response.customer.size - 1, { index ->
payload.append('"name": "').append(response.customer[index].name).append('"')
if (index != response.customer.size - 1) {
payload.append(',')
}
})
payload.append('}]')
vars.put('payload', payload as String)
Refer the generated value as ${payload} where required
Demo:
More information:
JsonSlurper
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Filtering/Selecting array values from index in Json in groovy

Trying to filter selective index. Fieldid values changes with every build, What do not change is fieldName": "TX.Sessionval.cost". Need to filter out the whole stringval and save into variable
fieldName": "TX.Sessionval.cost"
[
{
"Fieldid": "Fieldid/112",
"fieldName": "TX.Sessionval.cost",
"stringval": "jklah-dw-4c8d-8320-das313s3ASsda|000725N8WuUrfwAS7alP|banker_name"
}
]
tried def slurper = new JsonSlurper() def result = slurper.parseText(response.getResponseBodyContent()) def newf = result.findAll { it.contains("TX.Sessionval.cost") } getting groovy.lang.MissingMethodException: No signature of method: java.util.LinkedHashMap$Entry.contains()
in Postman locator works fine
postman.setEnvironmentVariable("Stdid", jsonData.newFields[112].stringValue)
Your JSON in your question is wrong. Extrapolating from your working
code, this should work:
result.newFields.find{ it.fieldName == "TX.Sessionval.cost" }?.stringValue
This works with me result.newFields.findAll { Map map -> map.get("fieldName").contains("TX.Sessionval.cost") }?.stringValue

Getting values from json array using an array of object and keys in Python

I'm a Python newbie and I'm trying to write a script to extract json keys by passing the keys dinamically, reading them from a csv.
First of all this is my first post and I'm sorry if my questions are banals and if the code is incomplete but it's just a pseudo code to understand the problem (I hope not to complicate it...)
The following partial code retrieves the values from three key (group, user and id or username) but I'd like to load the objects and key from a csv to make them dinamicals.
Input json
{
"fullname": "The Full Name",
"group": {
"user": {
"id": 1,
"username": "John Doe"
},
"location": {
"x": "1234567",
"y": "9876543"
}
},
"color": {
"code": "ffffff",
"type" : "plastic"
}
}
Python code...
...
url = urlopen(jsonFile)
data = json.loads(url.read())
id = (data["group"]["user"]["id"])
username = (data["group"]["user"]["username"])
...
File.csv loaded into an array. Each line contains one or more keys.
fullname;
group,user,id;
group,user,username;
group,location,x;
group,location,y;
color,code;
The questions are: can I use a variable containing the object or key to be extract?
And how can I specify how many keys there are in the keys array to put them into the data([ ][ ]...) using only one line?
Something like this pseudo code:
...
url = urlopen(jsonFile)
data = json.loads(url.read())
...
keys = line.split(',')
...
# using keys[] to identify the objects and keys
value = (data[keys[0]][keys[1]][keys[2]])
...
But the line value = (data[keys[0]][keys[1]][keys[2]]) should have the exact number of the keys per line read from the csv.
Or I must to make some "if" lines like these?:
...
if len(keys) == 3:
value = (data[keys[0]][keys[1]][keys[2]])
if len(keys) == 2:
value = (data[keys[0]][keys[1]])
...
Many thanks!
I'm not sure I completely understand your question, but I would suggest you to try and play with pandas. It might be as easy as this:
import pandas as pd
df = pd.read_json(<yourJsonFile>, orient='columns')
name = df.fullname[0]
group_user = df.group.user
group_location = df.group.location
color_type = df.color.type
color_code = df.color.code
(Where group_user and group_location will be python dictionaries).

Dynamic JSON Formatting Issue

My application reads JSON data in a particular format. I am pulling data from a database to dynamically create the data. I have the data, I just do not know the proper way to put it all in the following format.
Note: the first 2 sets are pulled from one query, and the "variables" section is what needs to be looped through to populate as the variable names AND values are in their own fields.
Sample Tables<br>
Master Table
ID | Custom_Col1 | Custom_Col2
1 custom_val1 custom_val2
Variables Table
ID | Name | Value
1 var_name1 var_value1
2 var_name2 var_value2
3 var_name3 var_value3
4 var_name4 var_value4
5 var_name5 var_value5
6 var_name6 var_value6
{"Custom_Col1":"custom_val1", "Custom_Col2":"custom_val2","variables":{"var_name1":"var_value1","var_name2":"var_value2","var_name3":"var_value3", "var_name4":"var_value4","var_name5":"var_value5","var_name6":"var_value6"}}
I was able to get the looped values in by using the following, but I just don't know how to get the other variables in. I'm sure it's simple, I've just never worked with JSON before. I've scoured the internet and have found examples, but they have only gotten me so far:
var json = {}
while loop
{
json[name]= value.toString();
}
var stringJson = JSON.stringify(json);
You can create a collection in the same way you did with the var json.
var json = {}
while loopMasterTable
{
json[name]= value.toString();
}
json['variables'] = {}
while loopVariableTable
{
json['variables'][name]= value.toString();
}
var stringJson = JSON.stringify(json);
This will give you the following JSON:
{
"Custom_Col1": "custom_val1",
"Custom_Col2": "custom_val2",
"variables": {
"var_name1": "var_value1",
"var_name2": "var_value2",
"var_name3": "var_value3",
"var_name4": "var_value4",
"var_name5": "var_value5",
"var_name6": "var_value6"
}
}

How can I sort based on children?

Using Vapor and Fluent (PostgreSQL if that matters) I have entity B that has aID: Node (A is B's parent) to reference A and A has a one-to-many relationship with B. How can I make a query to fetch all A's sorted by the count of B's?
I want the result to look something like this:
All A's in DB
[
{
"id": 4,
"name": "Hi",
"bCount": 1000
},
{
"id": 3,
"name": "Another",
"bCount": 800
},
{
"id": 5,
"name": "Test",
"bCount": 30
}
]
Firstly,
Create a modal for A
Turn that JSON string to array of A
if you do this your sorting becomes as easy as -
array.sort { $0.bCount < $1.bCount }
This is going to be tricky to implement entirely in Fluent using Entity. Firstly, you will need to use raw SQL to get your bCount. Secondly, you will need to change your init(node:) to accept bCount, though it shouldn't be in your makeNode() because we don't want to create a stored database field for it.
Try this for your raw SQL (untested):
SELECT
A.*,
(
SELECT COUNT(*)
FROM B
WHERE B.aID = A.id
) AS bCount
FROM A
ORDER BY bCount
Then, run that query to get your A models.
var models: [A] = []
if let driver = drop.database?.driver as? PostgreSQLDriver {
if case .array(let array) = try driver.raw(sql) {
for result in array {
do {
var model = try A(node: result)
models.append(model)
}
}
}
}
As I said before, your init method on A will be receiving bCount so you will need to store it there.

Resources