Building complete JSON in grails - json

My controller looks like this:
def save() {
js {
def color = new Color(params)
color.save()
def result
if (!color.hasErrors())
{
result = [colorname: color.name, colorshde: color.shade]
}
else
{
result = "..."
}
render result as JSON
}
}
The JSON that I desire should look like this:
Successful JSON
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"color": {
"colorname": "Red",
"shade": "light
}
}
}
Unsuccessful response:
{
"meta": {
"status": 400,
"msg": "Something went worn"
},
"response": {
"color": {
}
}
}
Question
How can I modify the controller action to account for both scenarios while returning json?

For successful response:
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"color": {
"colorname": "Red",
"shade": "light
}
}
}
Use:
result = [meta: [status: '200', msg: 'OK'], response:[color:[colorname: color.name, colorshde: color.shade] ] ]
For unsuccessful response:
{
"meta": {
"status": 400,
"msg": "Something went worn"
},
"response": {
"color": {
}
}
}
Use
result = [meta: [status: '400', msg: 'wrong'], response:[color:[] ] ]

Related

how can i insert a Netsuite inventory adjustment with lot numbered items with suitetalk?

I don't know how to configure the inventory detail in the JSON
I'm trying to POST at https://<>.suitetalk.api.netsuite.com/services/rest/record/v1/inventoryAdjustment
this JSON
{
"account": 4738,
"trandate":"2022-11-14",
"subsidiary":3,
"inventory":
{
"items":
[
{
"item": 9908,
"location":25,
"adjustQtyBy": 100,
"memo":"m-203174 p-21992 c-TM/55 #2"
,
"inventoryDetail":
{
"inventoryAssignment":
[
{
"receiptInventoryNumber": 2002111,
"quantity": 100
}
]
}
}
]
}
}
but i'm receiving this error:
{
"type": "https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1",
"title": "Bad Request",
"status": 400,
"o:errorDetails": [
{
"detail": "Error while accessing a resource. You still need to reconfigure the inventory detail record after changing the quantity.",
"o:errorPath": "inventory.items[0]",
"o:errorCode": "USER_ERROR"
}
]
}
i got this second error after changing inventorydetail section:
{
"type": "https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1",
"title": "Bad Request",
"status": 400,
"o:errorDetails": [
{
"detail": "Invalid content in the request body.",
"o:errorCode": "INVALID_CONTENT"
}
]
}
Now it works
{
"account": 4737,
"trandate":"2022-11-14",
"subsidiary":3,
"inventory":
{
"items":
[
{
"item": 9908,
"location":25,
"adjustQtyBy": 100,
"memo":"P$203174$21992$TM/55$2"
,
"inventoryDetail":
{
"inventoryAssignment":
{
"items":
[
{
"receiptInventoryNumber": 2002111,
"quantity": 100,
"expirationDate":"2022-11-30"
}
]
}
}
}
]
}
}

Add JSON Object to array

After first system call fails, i am getting this json.
{
"header": {
"msgCode": "400",
"message": "Call failed!"
},
"body": {
"success": false,
"error_list": [
]
}
}
After every next system call fails, i am getting receipt_code, which i have to append to above json.
{
"header": {
"msgCode": "400",
"message": "Call failed!"
},
"body": {
"success": false,
"error_list": [
{
"errors": [
{
"message": "Invalid receipt code!"
}
],
"receipt_code": "A-11277809" //here is receipt_code
}
]
}
}
for all next calls if fail, then keep on appending this.
{
"header": {
"msgCode": "400",
"message": "Call failed!"
},
"body": {
"success": false,
"error_list": [
{
"errors": [
{
"message": "Invalid receipt code!"
}
],
"receipt_code": "11111"
},
{
"errors": [
{
"message": "Invalid receipt code!"
}
],
"receipt_code": "1222"
}
]
}
}
how can this be done by Groovy, any help
Here is my code
if(success!="true")
{
def receipt_code=receiptList[receiptFlag].receipt_code;
def error_list = []
def error ={
"errors": [
{
"message": "Invalid receipt code!"
}
],
"receipt_code": receipt_code //here is receipt_code
}
error_list.push(error)
error_list = JSON.stringify(error_list)
msg.put("error_list",error_list);
}
I am not able to add using above code
Using JsonSlurper
import groovy.json.*
String text = """
{
"header": {
"msgCode": "400",
"message": "Call failed!"
},
"body": {
"success": false,
"error_list": [
]
}
}
"""
def json = new JsonSlurper().parseText(text)
errors = [
['errors': [['message': 'hi']], 'code': 100],
['errors': [['message': 'hello']], 'code': 200]
]
for (err in errors)
json.body.error_list << err
println JsonOutput.toJson(json)
Output
{
"header": {
"msgCode": "400",
"message": "Call failed!"
},
"body": {
"success": false,
"error_list": [
{
"errors": [
{
"message": "hi"
}
],
"code": 100
},
{
"errors": [
{
"message": "hello"
}
],
"code": 200
}
]
}
}

Json object in URI

I am trying to query my elastic search server in python, If I hard coded the url and query string like below in my python (search()) script working fine no issues. If I want to store those url and query in a separate xml file (property file). I'm not getting the results instead I got the below error:
text '{"error":{"root_cause":[{"type":"parsing_exception","reason":"Expected [START_OBJECT] but found [VALUE_STRING]","line":1,"col":1}],"type":"parsing_exception","reason":"Expected [START_OBJECT] but found [VALUE_STRING]","line":1,"col":1},"status":400}' str
Here is my code I am using
def search():
url="http://0.0.0.0/logstash-pse*/_search/"
query={ "size": 0, "aggs": { "2": { "date_histogram": { "field": "#timestamp", "interval": "30m", "time_zone": "America/Chicago", "min_doc_count": 1 }, "aggs": { "3": { "terms": { "field": "queryname.keyword", "size": 100, "order": { "1.90": "desc" } }, "aggs": { "1": { "percentiles": { "field": "queryResponseTime", "percents": [ 90 ], "keyed": "false" } } } } } } }, "query": { "bool": { "must": [ { "query_string": { "query": "path: \"/store_locator/\"", "analyze_wildcard": "true" } }, { "query_string": { "analyze_wildcard": "true", "query": "*" } }, { "range": { "#timestamp": { "gte": 1527181463371, "lte": 1527267863371, "format": "epoch_millis" } } } ], "must_not": [] } }, "highlight": { "pre_tags": [ "#kibana-highlighted-field#" ], "post_tags": [ "#/kibana-highlighted-field#" ], "fields": { "*": { "highlight_query": { "bool": { "must": [ { "query_string": { "query": "path: \"/store_locator/\"", "analyze_wildcard": "true", "all_fields": "true" } }, { "query_string": { "analyze_wildcard": "true", "query": "*", "all_fields": "true" } }, { "range": { "#timestamp": { "gte": 1527181463371, "lte": 1527267863371, "format": "epoch_millis" } } } ], "must_not": [] } } } }, "fragment_size": 2147483647 }, "_source": { "excludes": [] }, "version": "true"}
response = requests.post(url, auth=(user, password), verify=False,json=query)
XML property file I am using like the below:
<custom>
<url>the above url goes here</url>
<query> above query </query>
</custom>
Any idea what I am missing?, Much appreciated
Able to figure it out with few exercise on my own. In case if someone is looking for:
I just used the below
response = requests.post(url, auth=(user, password), verify=False,json=json.loads(query))

How to send carousel through API.AI?

My bot wants to send a carousel to Google Assistant through API.AI. My understanding is, I need to enclose it inside data -> google, such as:
{
"data": {
"google": {
"expectUserResponse": true,
"isSsml": false,
"expectedInputs": [
{
"inputPrompt": {
"richInitialPrompt": {
"items": [
{
"simpleResponse": {
"textToSpeech": "Hello World"
}
}
]
}
},
"possibleIntents": [
{
"intent": "actions.intent.OPTION",
"inputValueData": {
"#type": "type.googleapis.com/google.actions.v2.OptionValueSpec",
"carouselSelect": {
"items": [
{
"optionInfo": {"key": "FOO", "synonyms": ["foo"]},
"title": "Foo",
"image": {"url": "http://example.com/", "accessibilityText": "Foo"}
},
{
"optionInfo": {"key": "BAR", "synonyms": ["bar"]},
"title": "Bar",
"image": {"url": "http://example.com/", "accessibilityText": "Bar"}
}
]
}
}
}
]
}
]
}
}
}
But it doesn't work. What is the proper format?
If you are testing this through the Simulator, there should have been a validation error that appeared that would give you at least a little guidance about what is missing. If you didn't even get that, there may be a problem with the other parts besides the data.google object such that api.ai had problems with it.
There are a number of things that, at a glance, could be the problem. You can't just stick a conversation webhook response in the api.ai response. See https://developers.google.com/actions/apiai/webhook#response for the documentation, but here are a few things that I see that could be issues
The expectedInputs property shouldn't be there.
Your data.google.expectedInputs.possibleIntents property should be at data.google.systemIntent
You still need to provide the api.ai fields, such as a basic speech property
The data.google.expectedInputs.inputPrompt.richInitialPrompt would be at data.google.richResponse
Here is some JSON that works for me:
{
"speech": "Hello",
"contextOut": [
{
"name": "_actions_on_google_",
"lifespan": 100,
"parameters": {}
}
],
"data": {
"google": {
"expectUserResponse": true,
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "Hello"
}
}
],
"suggestions": []
},
"systemIntent": {
"intent": "actions.intent.OPTION",
"data": {
"#type": "type.googleapis.com/google.actions.v2.OptionValueSpec",
"carouselSelect": {
"items": [
{
"title": "Foo",
"image": {
"url": "http://example.com/foo.jpg",
"accessibilityText": "Foo title"
},
"optionInfo": {
"key": "foo-key",
"synonyms": [
"foo-alt-1",
"foo-alt-2"
]
}
},
{
"title": "Bar",
"image": {
"url": "http://example.com/bar.jpg",
"accessibilityText": "Bar title"
},
"optionInfo": {
"key": "bar-key",
"synonyms": [
"bar-alt-1",
"bar-alt-2"
]
}
}
]
}
}
}
}
}
}

Convert watches elasticsearch output to json with groovy

I want to convert payload.hits.hits to json in elasticsearch watcher output. I found as a solution groovy transform script :
PUT _watcher/watch/error_alert
{
"trigger": {
"schedule": {
"interval": "1m"
}
},
"input": {
"search": {
"request": {
"body": {
"query": {
"bool": {
"must": [
{
"query_string": {
"default_field": "message",
"query": "ERROR"
}
},
{
"range": {
"#timestamp": {
"gte": "now-1m",
"lte": "now"
}
}
}
]
}
}
}
}
}
},
"condition": {
"compare": {
"ctx.payload.hits.total": {
"gt": 0
}
}
},
"transform" : {
"script" : "return [ body: groovy.json.JsonOutput.toJson(ctx.payload.hits.hits)]"
},
"actions": {
"some_webhook": {
"webhook": {
"method": "POST",
"host": "*.*.*.*",
"port": 4000,
"path": "/sms",
"headers": {
"Content-Type": "application/json"
},
"body": "message: {{ctx.payload.body}}"
}
}
}
}
This request returns this exception:
"type": "general_script_exception",
"reason": "failed to compile script [ScriptException[compile error]; nested: IllegalArgumentException[Variable [body] is not defined.];]"
I have tried many alternative solutions but it seems that it works for most of people except me!
I use:
Elasticsearch 5.3.0
Kibana 5.0.2
Can someone help me please !
Looks like a syntax issue in your json.
"return [ body: groovy.json.JsonOutput.toJson(ctx.payload.hits.hits)]"
Try
"return { 'body': JsonOutput.toJson(ctx.payload.hits.hits)}"