I am new to groovy and need to parse JSON response. the response looks like this:
[
{
"name": "John",
"start_date": "2016-09-30",
"sort_order": 1
},
{
"name": "Tony",
"start_date": "2016-06-30",
"sort_order": 2
}
]
How can I get each object from that? would like to end up with name, start_date and sort_order for each student together.
You would use JsonSlurper
import groovy.json.*
def json = '''[
{ "name": "John", "start_date": "2016-09-30", "sort_order": 1 },
{ "name": "Tony", "start_date": "2016-06-30", "sort_order": 2 } ]'''
def parsed = new JsonSlurper().parseText(json)
assert parsed.name == ['John', 'Tony']
Related
This is my serializer.py
class RefbookSerializer(serializers.ModelSerializer):
class Meta:
model = Refbook
fields = ['id', 'code', 'name']
And it's my views.py
class RefbookAPIList(ListCreateAPIView):
queryset = Refbook.objects.all()
serializer_class = RefbookSerializer
def get_queryset(self):
date = self.request.query_params.get('date', None)
if date:
query = Refbook.objects.filter(versions__date__lte=date).distinct()
return query
return super().get_queryset()
Now, on request
GET api/v1/refbooks/?date=2023-02-01
it returns a response like:
[
{
"id": 3,
"code": "1",
"name": "..."
},
{
"id": 4,
"code": "2",
"name": "..."
}
]
But i want like this:
{
"refbooks": [
{
"id": 3,
"code": "1",
"name": "..."
},
{
"id": 4,
"code": "2",
"name": "..."
}
]
}
How can i add this "refbooks" key and curly braces around it?
I have a json output that I have been able to parse successfully but I'm not able to read some of the properties value using groovy
From the below json data, I can parse this data
def parsedJsonGet = new groovy.json.JsonSlurper().parseText(Response)
def i = -1
parsedJsonGet.each {
thisRecord ->
i= i+1
//Here using thisRecord can go through each node
}
From the below json data I would like to read say Street value of each such nodes.
Json Code is in this format:
{
[
"Name": "ABC",
"Address": {
"":0,
"City": [
{
"Street": "Data1",
"Apt": "Data2",
"Pin": "Data3",
}
]
}
},
{
[
"Name": "ABC",
"Address": {
"":0,
"City": [
{
"Street": "",
"Apt": "",
"Pin": "",
}
]
}
}
Making a few assumptions about your payload, which isn't well-formed JSON, you could parse the data this way:
def Response = '''{
"Records": [
{
"Name": "ABC",
"Address": {
"Number": 0,
"City": [
{
"Street": "Data1",
"Apt": "Data2",
"Pin": "Data3"
}
]
}
}
]
} '''
def parsedJsonGet = new groovy.json.JsonSlurper().parseText(Response)
parsedJsonGet.Records.each {
thisRecord -> System.out.println('Street is ' + thisRecord.Address.City[0].Street)
}
Because City is an array, I'm assuming you want just the first City/Street record. This will return: This record is Data1
I need to export the JSON response values in jmeter to a CSV file. The Json response looks somewhat like the sample below. What would be the simplest approach to do this in Jmeter?
{
"messages": null,
"results": {
"aaa": [
{
"code": "123",
"name": "abc",
"primary": true
},
{
"code": "456",
"name": "def",
"primary": false
}
],
"bbb": null,
"ccc": [
{
"code": "789",
"name": "ghi",
"primary": false
},
{
"code": "222",
"name": "jkl",
"primary": true
}
]
},
"errors": null
}
I want the output csv to look something like this:
result, code, name (headers)
aaa, 123, abc
aaa, 456, def
ccc, 789, ghi
Not sure how many variable are there in your JSON but you can try on this website:
http://convertcsv.com/json-to-csv.htm
Usually i do online but putting my JSON format from browser to this link above and get extracted to .CSV
See if that helps, good luck.
Pre-condition:
I'm testing REST in SoapUI tool.
I'm sending request, and in result
I have json response, which I want to parse with help of groovy code:
{"List": [
{
"id": 1,
"data1": "xxx",
"data2": {
"node1": "1",
"node2": "4",
"node3": 1,
}
},
{
"id": 2,
"data1": "yyy",
"data2": {
"node1": "2",
"node2": "6",
"node3": 2,
}
},
{
"id": 3,
"data1": "zzz",
"data2": {
"node1": "2",
"node2": "6",
"node3": 2,
}
}
]}
Goal: I want to find certain block (e.g. that with "id" = 2), and continue to parse this block with the goal of further assertions.
E.g., I want to verify, that directly in the "block" with "id"=2, those node1/node2/node 3 are {2, 6, 2} correspondingly.
So, how to do it with groovy(in soapUI script step) ?
import groovy.json.JsonSlurper
def data = new JsonSlurper().parse ...
def e = data.List.find{it.id==1}
assert e.data1=="xxx"
I'm trying to write extract the name value "Acura" from a JSON array response by using the location of the value stored in a variable called "jsonFieldName".
Below is the code that I'm trying to do this with, however, everytime i run the script, SOAPUI returns error: "java.lang.NullPointerException: Cannot get property 'name' on null object error at line: 156"
Can someone kindly advise how to do this?
import groovy.json.JsonSlurper
def response = '''{
"makes": [
{
"id": 200002038,
"name": "Acura",
"niceName": "acura",
"models": [
{
"id": "Acura_ILX",
"name": "ILX",
"niceName": "ilx",
"years": [
{
"id": 200471908,
"year": 2014
}
]
},
{
"id": "Acura_ILX_Hybrid",
"name": "ILX Hybrid",
"niceName": "ilx-hybrid",
"years": [
{
"id": 200493809,
"year": 2014
}
]
},
{
"id": "Acura_MDX",
"name": "MDX",
"niceName": "mdx",
"years": [
{
"id": 200465929,
"year": 2014
}
]
},
{
"id": "Acura_RDX",
"name": "RDX",
"niceName": "rdx",
"years": [
{
"id": 200467168,
"year": 2014
}
]
},
{
"id": "Acura_RLX",
"name": "RLX",
"niceName": "rlx",
"years": [
{
"id": 100539511,
"year": 2014
}
]
},
{
"id": "Acura_TL",
"name": "TL",
"niceName": "tl",
"years": [
{
"id": 200488448,
"year": 2014
}
]
},
{
"id": "Acura_TSX",
"name": "TSX",
"niceName": "tsx",
"years": [
{
"id": 200490517,
"year": 2014
}
]
},
{
"id": "Acura_TSX_Sport_Wagon",
"name": "TSX Sport Wagon",
"niceName": "tsx-sport-wagon",
"years": [
{
"id": 200673755,
"year": 2014
}
]
}
]
},
{
"id": 200001769,
"name": "Aston Martin",
"niceName": "aston-martin",
"models": [
{
"id": "Aston_Martin_DB9",
"name": "DB9",
"niceName": "db9",
"years": [
{
"id": 200473436,
"year": 2014
}
]
},
{
"id": "Aston_Martin_Rapide_S",
"name": "Rapide S",
"niceName": "rapide-s",
"years": [
{
"id": 200460643,
"year": 2014
}
]
},
{
"id": "Aston_Martin_V8_Vantage",
"name": "V8 Vantage",
"niceName": "v8-vantage",
"years": [
{
"id": 200472947,
"year": 2014
}
]
},
{
"id": "Aston_Martin_Vanquish",
"name": "Vanquish",
"niceName": "vanquish",
"years": [
{
"id": 200431313,
"year": 2014
}
]
}
]
}
],
"makesCount": 2
}'''
def jsonFieldName = ('makes[0].name')
def json = new JsonSlurper().parseText (response)
jsonFieldName.split("\\.").each{json = json[it]}
assert json == 'Acura'
Assuming that your JSON is good from the response (check by calling print) Try adding .text to the end of your jsonSlurper() Call
It also looks like you have a space between parseText and (response)
so it should be
def json = new JsonSlurper().parseText(response)
However I would try casting to ArrayList<LazyMap> to ensure you can iterate by
ArrayList<LazyMap> json = new JsonSlurper().parseText(response) as ArrayList<LazyMap>
Then call :
json.get('Acura')
This line of your code doesn't handle the index resolution:
jsonFieldName.split("\\.").each{json = json[it]}
There is no key with the name makes[0]. Instead there is an array of makes and you are interested on the first one. The following hardcoded line retrieves the name attribute:
def result = json.'makes'[0].'name'
As you can see here there is an additional step to resolve the index operator. Of course you can implement this functionality on your own or use JsonPath instead of JsonSlurper.
OK so I managed to get this working by using JsonPath instead of JsonSlurper.
To achieve this I had to import the following:
import com.jayway.jsonpath.JsonPath
def jsonFieldName = "makes[0].name"
def expectedValue = "Acura"
def jsonSuff = JsonPath.read(response, jsonFieldName)
log.info(jsonSuff)
if (jsonSuff.toString() == expectedValue.toString()){
log.info("Actual value"+jsonSuff+"is equal to expected value"+expectedValue)
}