Json Escape Character Traversin [duplicate] - json

I cannot get the inner nested key's value of this json object (it gets response from our API call, I just only copy the response from karate)
[
{
"code": 200,
"result": "[{\"distinct\":false,\"operatetime\":\"2019-05-17 17:01:01\",\"personid\":\"e8edec61-fd1a-4c69-8b60-fb8d21d06095\",\"sampleid\":\"1c9410cd-608d-4eb1-8d12-c8f2faf7fca4\"}]"
}
]
And def tempreponse = [{"code":200,"result":"[{\"distinct\":false,\"operatetime\":\"2019-05-17 17:01:01\",\"personid\":\"e8edec61-fd1a-4c69-8b60-fb8d21d06095\",\"sampleid\":\"1c9410cd-608d-4eb1-8d12-c8f2faf7fca4\"}]"}]
And def temp1 = tempreponse[0].result <- this sentence works
And def temp1 = tempreponse[0].result[0] <- however, this doesn't work, the print of temp1 is blank
In fact, I need to get the value of personid and sampleid, but failed

Yeah your response looks really wrong, a string within a JSON and all. But even if that is the expected response, Karate can handle it. Refer the documentation on type conversions: https://github.com/intuit/karate#type-conversion
* def response =
"""
[
{
"code": 200,
"result": "[{\"distinct\":false,\"operatetime\":\"2019-05-17 17:01:01\",\"personid\":\"e8edec61-fd1a-4c69-8b60-fb8d21d06095\",\"sampleid\":\"1c9410cd-608d-4eb1-8d12-c8f2faf7fca4\"}]"
}
]
"""
* json result = response[0].result
* def personId = result[0].personid
* match personId == 'e8edec61-fd1a-4c69-8b60-fb8d21d06095'

Related

Apache Nifi manipulate nested json with Execute Script

I am looking for a way to update the given Json's values and keys in a dynamic way. The way the Json is delivered is Always the same(in Terms of structure). The only Thing that differs is the amount of Data that is provided. So for example there could sometimes be 30, sometimes only 10 nestings etc.
…
"ampdata": [
{
"nr": "303",
"code": "JGJGh4958GH",
"status": "AVAILABLE",
"ability": [ "" ],
"type": "wheeled",
"conns": [
{
"nr": "447",
"status": "",
"version": "3",
"format": "sckt",
"amp": "32",
"vol": "400",
"vpower": 22
}
]
}
As Json uses other keys/values than I in my DB, I Need to convert them. Additionally I Need to Change some values if they match explicit strings.
So for example: "Code" has to be renamed to"adrID" and "sckt" should map to the values "bike".
I tried a simple Groovy-Script to remove the key and or Change the value. There is no Problem in changing values, but in changing the key itself. So I tried removing the key and adding a new key. Unfortunately I could not figure out how to add a new key:value to the given json. So how can I add a new pair of key:value or rename the key, if that´s possible. Have a look at my code-example
def flowFile = session.get()
if (!flowFile) return
try {
flowFile = session.write(flowFile,
{ inputStream, outputStream ->
def text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
def obj = new JsonSlurper().parseText(text)
def objBuilder = new JsonBuilder(obj)
// Update ingestionDate field with today's date
for(i in 0..obj.data.size()-1){
obj.data[0].remove("postal_code")
objBuilder.data[0].postal_code=5
}
// Output updated JSON
def json = JsonOutput.toJson(obj)
outputStream.write(JsonOutput.prettyPrint(json).getBytes(StandardCharsets.UTF_8))
} as StreamCallback)
flowFile = session.putAttribute(flowFile, "filename", flowFile.getAttribute('filename').tokenize('.')[0]+'_translated.json')
session.transfer(flowFile, REL_SUCCESS)
} catch(Exception e) {
log.error('Error during JSON operations', e)
session.transfer(flowFile, REL_FAILURE)
}
...
def obj = new JsonSlurper().parse(inputStream, "UTF-8")
obj.data.each{e->
def value = e.remove("postal_code")
//set old value with a new key into object
e["postalCode"] = value
}
//write to output
def builder = new JsonBuilder(obj)
outputStream.withWriter("UTF-8"){ it << builder.toPrettyString() }

How to sort json data in groovy in alphabetic order?

I want to sort an json data which is like this
def json = []
for ( int i=10;i>1;i--){
if (i==10 || i==9 ){
json << [ name:"xyz",
id:i
]
}else
if (i==8 || i==7 ){
json << [ name:"abc",
id:i
]
}
}
// def jsondata = [success:true, rows:json]
def jsondata = [success:true, rows:json.sort(false) { it.name }]
print jsondata​
groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.sort() is applicable for argument types: (java.lang.Boolean, com.cs.AdminController$_closure15_closure83) values: [false, com.cs.controllers.AdminController$_closure15_closure83#3e020351]
Possible solutions: sort(), sort(java.util.Comparator), sort(groovy.lang.Closure), wait(), size(), size()
I want that data to be sorted alphabetic order ascending or descending
above one is working in a groovy console but not in my program , do i need to add something else like lib ?
Your output format seems to have no similarity to your code you posted
Also, your code you posted cannot just be run by someone trying to answer this question.
So this will be an educated guess...
Try:
def jsondata = [success:true, rows:json.sort(false) { it.name }, total:totalCount]
If you're using groovy from way back in the day for some unknown reason, then just drop the false, but beware as this will mutate your json list...
def jsondata = [success:true, rows:json.sort { it.name }, total:totalCount]

Getting the name of each field in JSON

I'm trying to parse a random JSON file in Grails.
First I need to get the name of each field
For example, given below JSON file,
{
"abbreviation": "EX",
"guid": "1209812-1l2kj1j-fwefoj9283jf-ae",
"metadata": {
"dataOrigin": "Example"
},
"rooms":
[
],
"site": {
"guid": "1209812-1l2kj1j-fwefoj9283jf-ae"
},
"title": "Example!!"
}
I want to find out the structure of the JSON file(lists of keys maybe), for example I want to save the list of keys such as 'abbreviation', 'guid', 'metadata', 'rooms', 'site', 'title' from this JSON file.
How would I do this?
(We need the name of the keys in order to get the value of that key, so with a arbitrarily structured JSON file I need to find out the keys first)
You can try below code
def filePath = "JSONFILE.json"
def text = new File(filePath).getText()
def json = JSON.parse(text)
def jsonKeys = json.collect{it.key}
println(jsonKeys)
This will print all json keys
From what dmahaptro commented, I figured out how to get all the keys within a JSON object.
Here is a simple sample code I wrote to test it
String jsonFile = new JsonSlurper().parseText(new URL(path to the json file).text)
JSONArray jsonParse = new JSONArray(jsonFile)
int len = jsonParse.length()
def names = []
def keys = []
(0..len-1).each {
JSONObject val = jsonParse.getJSONObject(it)
int numKeys = val.length()
names = val.names()
keys = val.keySet()
(0..numKeys-1).each {
def field = names[it]
println field +" : " + val."${field}"
}
}
This will print the key:value pair given a JSON file.

JSON with duplicate key names losing information when parsed

So either I go back and tell someone that they should fix their JSON, or I need to find out what I am doing wrong. Here is the JSON, notice that parameter occurs three times:
String j= '''{
"jobname" : "test",
"parameters" : {
"parameter": {"name":"maxErrors", "value":"0"},
"parameter": {"name":"case", "value":"lower"},
"parameter": {"name":"mapTable", "value":"1"}
}
} '''
And I am trying to get each name & value. My code
def doc = new JsonSlurper().parseText(j)
def doc1 = doc.entrySet() as List
def doc2 = doc.parameters.entrySet() as List
println "doc1.size===>"+doc1.size()
println "doc1===>"+doc1
println "doc2.size===>"+doc2.size()
println "doc2===>"+doc2
And my results:
doc1.size===>2
doc1===>[jobname=test, parameters={parameter={name=mapTable, value=1}}]
doc2.size===>1
doc2===>[parameter={name=mapTable, value=1}]
How come I only get one parameter? Where are the other two? It looks like JSON only keeps one parameter and discards the other ones.
The JSON is not in the correct format. There should not be duplicate key in the same hierarchy or they will override each other.
It should have been an array of paramters.
Like this,
String j= '''{
"jobname" : "test",
"parameters" : [
{"name":"maxErrors", "value":"0"},
{"name":"case", "value":"lower"},
{"name":"mapTable", "value":"1"}
]
}

JSON to Groovy with JsonSlurper and unknown "string"

I am writing a Grails/Groovy app and I have a JSON object with a "string" name (grommet and widget) inside the params member that can change. That is, next time it might be acme and zoom. Here is the JSON:
def jx = """{
"job": "42",
"params": {
"grommet": {"name": "x", "data": "y"},
"widget": { "name": "a", "data": "b"}
}
}"""
I am trying to figure out how to get the string grommet . Code so far:
def dalist = new JsonSlurper().parseText(jx)
println dalist.job // Gives: 42
println dalist.params // Gives: [grommet:[name:x, data:y], widget:[name:a, data:b]]
println dalist.params[0] // Gives: null
Any idea how to get the string grommet? Iama going to keep hitting my head against a wall.
The params key on the JSON object is associated with a JSON object, not an array, so you cannot access it by index. JsonSlurper maps JSON objects to Groovy Maps, so you can access params by its keys, which are strings, e.g. dalist.params.grommet, which will give you the map [name: 'x', data: 'y'].
To access the keys on the params you can do dalist.params.keySet(), which will give you the list ['grommet', 'widget']. If you are interested in just knowing params keys, that should do the trick. If you need to get the 'grommet' string for some reason, you can do it by accessing the first element on that list, i.e. dalist.params.keySet()[0], but i don't know why you would want to know that. And i'm not sure if it is guaranteed that the first key of that map will always be 'grommet', as JSON objects are unordered by the spec (from json.org: An object is an unordered set of name/value pairs), but, in turn, Groovy maps are ordered (the default implementation is LinkedHashMap)... so i would assume that the order is preserved when parsing JSON to the Groovy world, but i'd try not to rely on that particular behavior hehe.
It's Map instance, try:
def params = dalist.params.entrySet() as List // entrySet() returns Set, but it's easier to use it as a List
println params
println params.size()
println params[0]
println params[0].key
println params[0].value
This might help you.
import groovy.json.JsonSlurper;
def jx='{"job":"42","params":{"grommet":{"name":"x","data":"y"},"widget":{"name":"a","data":"b"}}}'
def dalist = new JsonSlurper().parseText( jx )
assert dalist.params.getClass().name == "java.util.HashMap";
assert dalist.params.size() == 2;
def keys = dalist.params.collect{ a, b -> a}; // returns "[grommet, widget]"
assert !!dalist.params.get( "grommet" ) == true