I'm using Grails 1.3.6. I read the following JSON into a variable ...
{
"abc": {
"attr1": "value1",
"attr2": "value2"
},
"def": {
"attr1": "value1",
"attr2": "value2"
},
"ghi": {
"attr1": "value1",
"attr2": "value2"
},
...
}
If, in my controller, I'm passed a parameter referring to one part of the JSON object ...
def section = params.section; // could be "abc", "def", 'ghi", ...e
How do I access that part of the JSON assuming the above gets stored into a Groovy variable named "myJSONObject"? Thanks, - Dave
If you used JSON.parse() to create your myJSONObject, you can just do:
def value = myJsonObject[section]
Related
I have a Postman POST request, where response body looks like this:
{
"data": [
{
"object": "Answer",
"id": 507,
...
},
{
"object": "Answer",
"id": 208,
...
}
],...
In following DEL request this ids should be used in body as array:
{
"ids": [id1, id2]
}
How can i get these ids from response and store it as environment variable array [id1, id2] so then it could be used like "ids": {{answer_ids_array}} ?
To capture the id values as an array and set in an environment variable you could add something like this to the Tests tab of the first request:
let myArray = []
_.each(pm.response.json().data, (item) => {
myArray.push(item.id)
})
pm.environment.set("idArray", myArray)
To use the array in the request body, you would need to add this to the Pre-request script to transform to saved string back into an array:
pm.environment.set("ids", JSON.stringify(pm.environment.get("idArray")))
Your request body would then be something like this:
{
"ids": {{ids}}
}
I have a json structure that I need to build up based on url parameters provided by a client. Currently I've been building the json structure out using Jbuilder.encode but it's getting pretty hairy.
self.query = Jbuilder.encode do |json|
json.query do
json.filtered do
json.filter do
json.bool do
if(search_term && username)
json.array!(should) do
........
How can I build ruby objects so that I convert them into json based on how they are initialized?
Below is the full json structure I'd like to capture in ruby models/poros (plain old ruby objects).
{
"query": {
"filtered": {
"filter": {
"bool": {
"should": [
{
"query": {
"query_string": {
"query": "tablet",
"fields": [
"standard_analyzed_name",
"standard_analyzed_message"
]
}
}
},
{
"term": {
"username": "feedmatic"
}
}
],
"must": [
{
"terms": {
"status_type": [
"3",
"4"
]
}
},
{
"range": {
"created_on": {
"gte": 20140712,
"lte": 1405134711
}
}
}
]
}
}
}
}
}
Hmm i'm not really sure about Poro's, but one thing I've seen is that when the structure starts to get hairy is to make a method that returns the hash representation of what you would like to show. Have you tried making a query method that returns a hash with that structure and then calling it in a jbuilder template?
There's an .attributes method for rails that returns a hash with the attributes, but you would have to look into how to use it with a PORO and if it works for this purpose.
I have this JSON and I am trying to send it to a Rails API from Postman:
{"object":
{
"type": "out",
"vars":
{
"x": "x",
"y": "y"
},
"values":
{
"ts": "timestamp",
"ok":
{
"total": 2,
"min": "x",
"max": "y"
},
"error":
{
"total": 2,
"error1": "first",
"error2": "second"
}
}
}
}
I need to convert this into a Hash in my model so that I can manipulate it with before_create. Here's what I came with:
object = self.to_json # => converts object to json
object = JSON.parse(object) # => converts json to hash
1st problem: I get this (id=>nil is not relevant since it will be inserted automatically in the database):
{"id"=>nil, "type"=>"out", "vars"=>{"x"=>"x", "y"=>"y"}, "values"=>{"ts"=>"timestamp", "ok"=>"{\"total\"=>2, \"min\"=>\"x\", \"max\"=>\"y\"}", "error"=>"{\"total\"=>2, \"error1\"=>\"first\", \"error2\"=>\"second\"}"}, "created_at"=>"2015-01-29T15:45:01.329Z", "updated_at"=>"2015-01-29T15:45:01.329Z"}
and when I try to manipulate object["values"]["ok"], Rails sends the error:
unexpected token at '"{\"total\"=\u003e2, \"min\"=\u003e\"x\", \"max\"=\u003e\"y\"}"'
2nd problem: I can only call object["values"], and I want to call it with a symbol, not a string object[:values].
Solved my issues using:
object = self.as_json.with_indifferent_access
# => allowing me to use a symbol key instead of a string
ok_vals = object[:values][:ok].as_json.gsub(/\=\>/, ':')
# => allowing to change json string '{"val1"=>"val1", "val2"=>"val2"}' to '{"val1":"val1", "val2":"val2"}'
ok_vals = JSON.parse(ok_vals)
# => which transform json string to hash {val1: "val1", val2: "val2"}
Feel free to make any suggestions to this code. Thanks for the help.
How do i get name=status using json path ... problem here is key=2 is random number,,, is their any way to skip these random and read name
Am using rest assured ,,this is sample response on GET request
Response
{
"error": false,
"message": "",
"data": {
"2": {
"name": "No Status",
"protected": "1",
"id": "1",
"temporal_start": "0",
"temporal_end": "2147483647"
},
"3": {
"name": "Started",
"protected": "1",
"id": "2",
"temporal_start": "0",
"temporal_end": "2147483647"
},
}
}
my request code is
given()
.param("error", "false")
.when()
.get(URI)
.then()
.body("data.2.name", startsWith(No))
I've found a solution but it's not very elegant:
when().
get(URI).
then().
body("data.collect { it.value }.reverse()[0].name", equalTo("No Status")).
body("data.collect { it.value }.reverse()[1].name", equalTo("Status"));
Which can be simplified using root paths:
when().
get(URI).
then().
root("data.collect { it.value }.reverse()[%d].name").
body(withArgs("0"), equalTo("No Status")).
body(withArgs("1"), equalTo("Status"));
Explanation:
Since data is a JsonObject represented as a HashMap we run the collect method to return only the values of the Map as a List. Then we reverse the list since it seems like the last when running collect the resulting list will have the last value first. Then we get the first value from this list (data.2 in your example) and finally get the name.
I am not sure what I am doing wrong here. I need to post an json object containing an array of objects + one extra root field. So for this code:
{
"root_field": "somedata",
"myobjects": [
{
"attr1": "1",
"attr2": 2",
"attr3": "3"
},
{
"attr1": "1",
"attr2": "2",
"attr3": "3"
}
]
}
I have this as code for strong parameters, which allows all myobjects in but fails to pass on the root_field, which is important in my application.
def my_params
params.require(:root_field)
params.require(:myobjects).map do |e|
ActionController::Parameters.new(e.to_hash).permit(:attr1,:attr2,:attr3)
end
end
Any thoughts?
If you want to while list root_field as a scalar value, it should be
params.permit(:root_field)
params.permit(:myobjects => [:attr1,:attr2,:attr3])