How to get array number with groovy script in SoapUI? - json

I want to assert the value of a property in Json response with the use of Groovy script in SoapUI. I know a value for name but I need to know on which position the id is.
json response example:
{
"names":[
{
"id":1,
"name":"Ted"
},
{
"id":2,
"name":"Ray"
},
{
"id":3,
"name":"Kev"
}
]
}
Let's say I know that there is a name Ray, I want the position and the id (names[1].id)

Here is the script to find the same:
import groovy.json.*
//Using the fixed json to explain how you can retrive the data
//Of couse, you can also use dynamic value that you get
def response = '''{"names": [ { "id": 1, "name": "Ted", }, { "id": 2, "name": "Ray", }, { "id": 3, "name": "Kev", } ]}'''
//Parse the json string and get the names
def names = new JsonSlurper().parseText(response).names
//retrive the id value when name is Ray
def rayId = names.find{it.name == 'Ray'}.id
log.info "Id of Ray is : ${rayId}"
//Another way to get both position and id
names.eachWithIndex { element, index ->
if (element.name == 'Ray') {
log.info "Position : $index, And Id is : ${element.id}"
}
}
You can see here the output

Related

Assert key name in the json response using groovy

I want to assert a key in the json response.
Response
{
"availableRooms": [
{
"roomId": 2,
"exchangeEmailId": null,
"roomName": "Room 1",
"floor": 0,
"groupID": 3,
"defaultCapacity": 8,
"maxCapacity": 8,
"attributes": [
{
"attributeID": 170,
"displayName": "Video Conference Unit",
"abbreviation": "VCU"
}
],
"externalRoomEmail": "vinay.jaiswal#condecosoftware.com"
}
],
"availableRoomsForAllDates": {},
"callResponse": {
"message": null,
"customResponseCode": null
}
}
Groovy
import groovy.json.JsonSlurper
def ResponseMessage = messageExchange.response.responseContent
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
if( jsonSlurper.containsKey( 'externalRoomEmail' ) )
{
log.info 'a'
}
else
{
log.info 'b'
}
Output
Tue Nov 24 20:24:35 IST 2020:INFO:b
Is there any inbuilt method?
If I try jsonSlurper.availableRooms.externalRoomEmail then it gives me null but testcase is passed.
I want that it should break the testcase if key not found.
<edit - just re-read your question, answer adjusted accordingly>
First of all I'm going to call your parsed json json instead of jsonSlurper as the slurper is the groovy class used to parse json and it's conceptually confusing to name the data "slurper".
So your problem is that json.availableRooms returns a list. In other words you would have to use something like:
if(json.availableRooms.first().externalRoomEmail) {
...
} else {
...
}
to check if the first room had an externalRoomEmail defined.
From there is depends on what you want to do. Let's say that you wanted to see if any of the available rooms had an externalRoomEmail defined, you would then do something like:
def roomsWithEmails = json.availableRooms.findAll { it.externalRoomEmail }
if (roomsWithEmails) {
roomsWithEmails.each { room ->
println "room ${room.roomName} has external email ${room.externalRoomEmail}"
}
} else { // no rooms with externalRoomEmail
// do something else
}

How to store json code in database table column in laravel

Hi guys i am trying to store my json data into my datatbase table column.
Here is my sample json code..this data only i am trying to store in db.
{
"template": {
"question_section": {
"section_data": [
{
"index": 1,
"section": "text section",
"properties": {
"font_size": "14",
"font_weight": "400",
"font_color": "#000000",
"row": 1
}
}
]
},
"solution_section": {
"section_data": []
}
}
}
here is my sample code:
function updateJson(field_id, from_where, section_counter, property_name, ques_section_counter, sol_section_counter)
{
if(from_where == 'question')
{
let prop_value = $('#'+field_id).val();
template_json.template.question_section.section_data[ques_section_counter-1].properties[property_name] = prop_value;
}
else if(from_where == 'solution')
{
let prop_value = $('#'+field_id).val();
template_json.template.solution_section.section_data[sol_section_counter-1].properties[property_name] = prop_value;
}
$('#code_json').html(JSON.stringify(template_json, undefined, 2));
}
This is one sample function that this is how i am getting json code and all..that above json wwhole code i would like to store.
Here is my form code:
$template->template_json = $request->input('');//this is the column
Can anyone help me on how can i store.
you have to save it as text in database like this:
$template->template_json = json_encode($request->input(''));
and then when you want to use it convert it to object before like this:
$template->template_json = json_decode($template->template_json);

How to insert an empty object into JSON using Circe?

I'm getting a JSON object over the network, as a String. I'm then using Circe to parse it. I want to add a handful of fields to it, and then pass it on downstream.
Almost all of that works.
The problem is that my "adding" is really "overwriting". That's actually ok, as long as I add an empty object first. How can I add such an empty object?
So looking at the code below, I am overwriting "sometimes_empty:{}" and it works. But because sometimes_empty is not always empty, it results in some data loss. I'd like to add a field like: "custom:{}" and then ovewrite the value of custom with my existing code.
Two StackOverflow posts were helpful. One worked, but wasn't quite what I was looking for. The other I couldn't get to work.
1: Modifying a JSON array in Scala with circe
2: Adding field to a json using Circe
val js: String = """
{
"id": "19",
"type": "Party",
"field": {
"id": 1482,
"name": "Anne Party",
"url": "https"
},
"sometimes_empty": {
},
"bool": true,
"timestamp": "2018-12-18T11:39:18Z"
}
"""
val newJson = parse(js).toOption
.flatMap { doc =>
doc.hcursor
.downField("sometimes_empty")
.withFocus(_ =>
Json.fromFields(
Seq(
("myUrl", Json.fromString(myUrl)),
("valueZ", Json.fromString(valueZ)),
("valueQ", Json.fromString(valueQ)),
("balloons", Json.fromString(balloons))
)
)
)
.top
}
newJson match {
case Some(v) => return v.toString
case None => println("Failure!")
}
We need to do a couple of things. First, we need to zoom in on the specific property we want to update, if it doesn't exist, we'll create a new empty one. Then, we turn the zoomed in property in the form of a Json into JsonObject in order to be able to modify it using the +: method. Once we've done that, we need to take the updated property and re-introduce it in the original parsed JSON to get the complete result:
import io.circe.{Json, JsonObject, parser}
import io.circe.syntax._
object JsonTest {
def main(args: Array[String]): Unit = {
val js: String =
"""
|{
| "id": "19",
| "type": "Party",
| "field": {
| "id": 1482,
| "name": "Anne Party",
| "url": "https"
| },
| "bool": true,
| "timestamp": "2018-12-18T11:39:18Z"
|}
""".stripMargin
val maybeAppendedJson =
for {
json <- parser.parse(js).toOption
sometimesEmpty <- json.hcursor
.downField("sometimes_empty")
.focus
.orElse(Option(Json.fromJsonObject(JsonObject.empty)))
jsonObject <- json.asObject
emptyFieldJson <- sometimesEmpty.asObject
appendedField = emptyFieldJson.+:("added", Json.fromBoolean(true))
res = jsonObject.+:("sometimes_empty", appendedField.asJson)
} yield res
maybeAppendedJson.foreach(obj => println(obj.asJson.spaces2))
}
}
Yields:
{
"id" : "19",
"type" : "Party",
"field" : {
"id" : 1482,
"name" : "Anne Party",
"url" : "https"
},
"sometimes_empty" : {
"added" : true,
"someProperty" : true
},
"bool" : true,
"timestamp" : "2018-12-18T11:39:18Z"
}

Ruby: How to parse json to specific types

I have a JSON that I want to parse in Ruby. Ruby is completely new to me, but I have to work with it :-)
Here is my litte snippet, that should do the parsing:
response = File.read("app/helpers/example_announcement.json")
JSON.parse(response)
this works pretty fine. The only downside is, I do not know the properties at the point where I use it, it is not typesafe. So I created the objects for it
class Announcements
##announcements = Hash # a map key => value where key is string and value is type of Announcement
end
class Announcement
##name = ""
##status = ""
##rewards = Array
end
And this is how the json looks like
{
"announcements": {
"id1" : {
"name": "The Diamond Announcement",
"status": "published",
"reward": [
{
"id": "hardCurrency",
"amount": 100
}
]
},
"id2": {
"name": "The Normal Announcement",
"players": [],
"status": "published",
"reward": []
}
}
}
So I tried JSON parsing like this
response = File.read("app/helpers/example_announcement.json")
JSON.parse(response, Announcements)
But this is not how it works^^can anybody help me with this?

Nodejs how to use map of object?

Hi i have a json like this called body:
{
data: {
id:1,
name:hallo
},
paging: {
cursors: {
next: "abc"
}
}
}
so I have to save it into a map and then I'll need to print or to modify it.
If I save it with this code
var Map = require("collections/map");
var new_body = JSON.parse(body)
var map = new Map(new_body);
I have some difficulties to print for example map.paging.cursor.next, how can I do it? maybe I had to define a structure of that map before inserting the json inside it, I don't know...
Your json have errors. Correct them like this.
{
"data": {
"id": 1,
"name": "hallo"
},
"paging": {
"cursors": {
"next": "abc"
}
}
}
Then you can parse the json like this and get the paging.cursors.next value.
var map = JSON.parse(body);//This will parse the json string
Now map.paging.cursors.next will have the value "abc"