Json Slupper assert and extract - json

I'm using the next Json
{
"ID": 8,
"MenuItems": [
{
"ID": 38,
"Name": "Home",
"URL": "{\"PageLayout\":\"Home\",\"Icon\":\"home\"}",
"Culture": "en",
"Children": null
},
{
"ID": 534,
"Name": "GUIDE ",
"URL": "{''PageLayout'':''Page A'', ''Icon'':''A''}",
"MenuType": 1,
"PageID": 0,
"Culture": "en",
"Children": [
{
"ID": 6,
"Name": "Form A",
"URL": "[''Type'':''Form A'',''Icon'':''Form'',''ItemID'':\"358\"]",
"Culture": "he",
"RuleID": 0
},
{
"ID": 60,
"Name": "Drama",
"URL": "[''Type'':''Form B'',''Icon'':''Form'',''ItemID'':\"3759\"]",
"Culture": "en",
"RuleID": 0
}
]
}
]
}
i'm using Groovy script in soapUI and i need to:
Assert the exitance of node that has the name GUIDE
Extract a list of all Itemsid

You can parse the JSON content using JsonSlurper and then work with the results like so:
import groovy.json.JsonSlurper
// Assuming your JSON is stored in "jsonString"
def jsonContent = new JsonSlurper().parseText(jsonString)
// Assert node exists with name GUIDE
assert(jsonContent.MenuItems.Name.contains("GUIDE"))
// Get list of ItemIDs
def itemList = jsonContent.MenuItems.Children.URL.ItemID[0].toList()
// List the items
itemList.each {log.info it}
Note that the above will fail given your current example, because of a few issues. Firstly, Name contains "GUIDE " (trailing space) rather than "GUIDE" (so you will need to adapt accordingly). Secondly, it is invalid JSON; the URL nodes have various erroneous characters.
On a side note, if you first need to retrieve your JSON from the response associated with a previous TestStep (say one called "SendMessage") within the existing testCase, this can be done as follows:
def jsonString = context.testCase.getTestStepByName("SendMessage").testRequest.response.getContentAsString()

Related

Concatenating lists in Groovy

I have captured two sets of values by using JSON extractor in JMeter which I want to concatenate. Let me give you an example below for the format which I want to use.
The following are the two sets of captured values:
Set 1: [V2520 V2522 V2521 V2500 V2500]
Set 2: [PL PL PL NP NP]
So from the above sets, I am looking for the something like the following value, because the body which I have to send in a subsequent call contains the combination of these 2 values:
Answer: ["V2520PL", "V2522PL", "V2521PL", "V2500NP", "V2500NP"]
Can you please help me how to solve this in JMeter using Groovy?
This is the JSON I have:
{ "body": {
"responseObject": [
{
"benefitInfo": [
{
"procedureCode": "V2520",
"modifier": "PL",
"usage": "Dress",
"authorizationID": null,
"description": "ContactLensDisposable",
"id": "96",
"coPayAmount": "25"
},
{
"procedureCode": "V2522",
"modifier": "PL",
"usage": "Dress",
"authorizationID": null,
"description": "ContactLensDisposableBifocal",
"id": "98",
"coPayAmount": "25"
},
{
"procedureCode": "V2521",
"modifier": "PL",
"usage": "Dress",
"authorizationID": null,
"description": "ContactLensDisposableToric",
"id": "97",
"coPayAmount": "25"
},
{
"procedureCode": "V2500",
"modifier": "NP",
"usage": "Dress",
"authorizationID": null,
"description": "ContactLens (Non Plan)",
"id": "89",
"coPayAmount": "0"
},
{
"procedureCode": "V2500",
"modifier": "NP",
"usage": "Dress",
"authorizationID": null,
"description": "ContactLensConventional (Non Plan)",
"id": "157",
"coPayAmount": "0"
}
]
}
]}}
An easy way to do this is to combine them as you collect the values from the JSON when you parse it.
def json = new groovy.json.JsonSlurper().parseText(text)
def answer = json.body.responseObject[0].benefitInfo.collect { it.procedureCode + it.modifier }
assert answer == ["V2520PL", "V2522PL", "V2521PL", "V2500NP", "V2500NP"]
Another method would be to use transpose() and join():
def r = new groovy.json.JsonSlurper().parseText(text).body.responseObject.benefitInfo[0]
def answer = [r.procedureCode, r.modifier].transpose()*.join()
assert answer == ["V2520PL", "V2522PL", "V2521PL", "V2500NP", "V2500NP"]
Add JSR223 PostProcessor as a child of the request which returns the above JSON
Put the following code into "Script" area:
def answer = []
def benefitInfos = com.jayway.jsonpath.JsonPath.read(prev.getResponseDataAsString(), '$..benefitInfo')
benefitInfos.each { benefitInfo ->
benefitInfo.each { entry ->
answer.add(entry.get('procedureCode') + entry.get('modifier'))
}
}
vars.put('answer', new groovy.json.JsonBuilder(answer).toPrettyString())
That's it, you will be able to access generated value as ${answer} where required:
References:
Jayway JsonPath
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Render Nested json objects in React Native

In my render() method i need to parse nested json objects. See the portion of render and json structure below.
I access Last Name with {params.name_last}.
How will i access items under team, like team.name_first
render() {
let { params } = this.props.navigation.state
<Text>{params.name_last}</Text>
}
[
{
"id": 1,
"name_first": "Name first 1",
"name_middle": "",
"name_last": "Name last 1",
"name_suffix": "",
"phone": "888-8888",
"fax": "888-8888",
"updated_at": "2015-11-02T21:42:42.000Z",
"team": [
{
"id": 16,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 28,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 29,
"name_first": "aaa ",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
}
]
}
]
Since team is an array, you need to either access a specific entry in the array, or iterate over the entire thing.
To reach a specific property in the nested array entry (assuming you want the object at index i):
params.team[i].name_first
To create an array of first names:
params.team.map(x => x.name_first)

How to get the the node object or array from JSON based on excel sheet data using groovy?

Lets say I have the following JSON :-
{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
And, I am passing the value of author from excel sheet to check if that author is present or not. If that author is present inside JSON, then that that particular array node only and remove other from the JSON.
For Example:- I am passing "author" value as "Herbert Schildt" from excel sheet. Now this value is present inside JSON, So, I need this particular array node to be printed and rest all should be removed. Like this:-
{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
}
]
}
Can it be done using groovy? I have tried with HashMap but couldn't get through.
It's quite easy using groovy:
def text = '''{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
'''
def result = groovy.json.JsonOutput.toJson(
[book: new groovy.json.JsonSlurper().parseText(text).book.findAll{it.author == "Herbert Schildt"}]
)
println result
You may try this ways json search
var json = '{"book":[{"id":"01","language":"Java","edition":"third","author":"Herbert Schildt"},{"id":"07","language":"C++","edition":"second","author":"E.Balagurusamy"}]}';
var parsed = JSON.parse(json);
var result = {};
result.book = [];
var author = "Herbert Schildt";
parsed.book.map((i, j) => {
if(i.author == author) {
result.book.push(i);
}
});
console.log(result)

JSON serialization technicalities in VB.NET

What is the difference between the following serialization methods?
First Method
JsonConvert.SerializeObject(list or datatable)
and the output is
i.e. (3) [Object, Object, Object]
Second Method
Dim parent = Prtdata
Dim lGridColumns = New With {
Key .data = parent
}
Dim Setting = New JsonSerializerSettings
Setting.PreserveReferencesHandling = PreserveReferencesHandling.Objects
Dim jsonObject = JsonConvert.SerializeObject(lGridColumns, Formatting.Indented)
Return jsonObject
and its output is
{
"data": [
{
"RecID": 2383,
"PrtStatus": 0,
"PtFilenum": 15090248,
"PrtFilenum": 13090701,
"FullName": "asdasd",
"DOB": "04 Oct 1985"
},
{
"RecID": 3387,
"PrtStatus": 1,
"PtFilenum": 15090248,
"PrtFilenum": 15120996,
"FullName": "marwam mohmmad saleem",
"DOB": "24 May 2017"
},
{
"RecID": 3388,
"PrtStatus": 1,
"PtFilenum": 15090248,
"PrtFilenum": 170227111,
"FullName": "asd dsf as a",
"DOB": "27 Feb 2017"
}
]
}
why the output looks different in the browser console?
As the first comment, you can find a Serialization Guide on the website of NewtonSoft.json, in my answer I just provide a more elaborate version of my comment earlier.
The first scenario, where you are serializing something implemented IEnumerable (eg: list, array), will be represented by an array in Json, eg:
[{ "property": "value", "id": 0 }, {"property": "value", "id": 1}]
For the second scenario, you are doing several things differently, for example you are providing the PreserveReferencesHandling in the JsonSerializerSettings which would also preveserve any references made in the objects you are serializing, eg:
[{"$id": 1, "title": "item1"}, {"$id": 2, "title": "item2", "previous": { "$ref": 1 }]
This would make sure that when deserialized, the second object would contain a reference to the first object, inside the property previous.
Another thing you are doing differently is providing the Formatting.Indented, which will create a more reader friendly json document, having line breaks and indentation. The previous Json would then become something similar to this:
[{
"$id": 1,
"title": "item1"
},
{
"$id": 2,
"title": "item2",
"previous": {
"$ref": 1
}
}]
And, the last big difference is that in the last example, you are serializing a single object, cause it's public properties to be serialized, eg:
{
"data": [
...
]
}
Where data is a property on the object you are serializing.

Rails 4: Trying to use Ancestry with jstree

I am new to Rails and trying to populate a jstree in the browser with JSON from the Ancestry gem (see https://github.com/stefankroes/ancestry). JSON is the go-between. Where I am stuck is translating the JSON produced (from my Tree model) by Ancestry:
<%= #trees.arrange_serializable.to_json %>
That gives me nice JSON as follows (fragment only, apologies for the nonsense values):
[
{
"id": 2,
"name": "Milk",
"note": "No details available",
"created_at": "2014-09-20T13:22:03.262Z",
"updated_at": "2014-09-20T13:48:46.301Z",
"value": "3.06",
"ancestry": null,
"children": [
{
"id": 1,
"name": "Farms",
"note": "Some note here",
"created_at": "2014-09-20T13:05:22.186Z",
"updated_at": "2014-10-03T11:30:39.029Z",
"value": "432.0",
"ancestry": "2",
"children": [
{
"id": 8,
"name": "Zog",
"note": "Orc",
"created_at": "2014-09-27T22:11:20.874Z",
"updated_at": "2014-10-03T11:30:38.989Z",
"value": "11.0",
"ancestry": "2/1",
"children": [
{
"id": 14,
"name": "Planes",
"note": "",
"created_at": "2014-10-04T01:01:12.890Z",
"updated_at": "2014-10-04T04:51:20.873Z",
"value": "422.0",
"ancestry": "2/1/8",
"children": []
}
]
},
but the jstree plugin requires a particular format for the JSON as follows (from http://www.jstree.com/docs/json/):
{
id : "string" // will be autogenerated if omitted
text : "string" // node text
icon : "string" // string for custom
state : {
opened : boolean // is the node open
disabled : boolean // is the node disabled
selected : boolean // is the node selected
},
children : [] // array of strings or objects
li_attr : {} // attributes for the generated LI node
a_attr : {} // attributes for the generated A node
}
While the source hierarchical structure is perfect, I need to replace the attribute "name" in the original with "text" in the output, plus a few other changes.
At the back of my mind I feel there should be something elegant (like XSLT for XML) to translate JSON#1 into JSON#2 but I can't find any examples that do this.