Here's an SQL query I had to execute in Groovy:
def resultset_bio = sql.rows("SELECT author, isbn FROM Book WHERE genre = 'biography'")
I'm trying to convert this data into JSON. For that, I am using this code:
def json = new groovy.json.JsonBuilder()
json {
Biographies(resultset_bio.collect{[id: it]})
}
println json.toPrettyString()
}
The JSON output I expect should be like this:
{
"Biographies":
{
"SSS": ["XXX",456988]
}
}
But instead, I'm getting this:
{
"Biographies": [
{
"id": {
"author": "XXX",
"isbn": 456988,
}
}
]
}
How should I change my code? Please help.
Now id is passed as a static key.
Try:
json {
Biographies(resultset_bio.collect{[(it.id): it]})
}
You do not have the book title in your select so you can't make a mapping of title to book info.
In order to get the list layout of each row (which is a map) grouped by author:
def authorBios = resultset_bio.groupBy { it.author }
def biographies = authorBios.collectEntries { author, row ->
[author, row*.values()]
}
json {
Biographies(biographies)
}
Related
in this json file I want to get original_ur but when i cant get it , can some one help me how to get it please
{
"orders": {
"order_items":[
{
"product_min":{
"colors":[
{
"media":[
{
"original_url": b
"https://royalpetiq.com/royalpet2/public//storage/10628/msg5212971698-890.jpg",
}
]
}
]
}
}
]
}
}
go on quicktype id site and create model from this json after just creat object of that claass and parse this json response and after that you can get valu like
x.orders.order_items[0].product_min.colors[0].media[0].original_url
here is your json path
x.orders.order_items[0].product_min.colors[0].media[0].original_url
try {
var json = """{
"orders": {
"order_items":[
{
"product_min":{
"colors":[
{
"media":[
{
"original_url": "https://royalpetiq.com/royalpet2/public//storage/10628/msg5212971698-890.jpg"
}
]
}
]
}
}
]
}
}""";
var data = jsonDecode(json);
var url = data["orders"]["order_items"][0]["product_min"]["colors"][0]
["media"][0]["original_url"];
print("Url: $url");
} catch (e) {
print(e);
}
I think your json should be like that.
Here the url has a b at the beginning and a comma after the url which is not the correct syntax for json
I have followed an example shown here
link
And i got the hang of it, i managed to create my own "Employee" entity and i found some dummy api data online to play with.
like this Problem is, the tornadofx throws null pointer error, and i think its because the rest response sends something like this
{
"status": "success",
"data": [
{
"id": "1",
"employee_name": "Tiger Nixon",
"employee_salary": "320800",
"employee_age": "61",
"profile_image": ""
},
but when i use mocky and provide JUST the json part
[
{
"id": "1",
"employee_name": "Tiger Nixon",
"employee_salary": "320800",
"employee_age": "61",
"profile_image": ""
},...]
it all works fine.
I think those additional fields "status" and "success" in response confuse the rest client of tornadofx, and i cant manage to get it to work, is there anyway to tell client to ignore every other fields besides those of json data.
All links are functional, so you can try yourself.
full working example
package com.example.demo.view
import javafx.beans.property.SimpleIntegerProperty
import javafx.beans.property.SimpleStringProperty
import javafx.scene.layout.BorderPane
import tornadofx.*
import javax.json.JsonObject
class Employee (id:Int?=null , name: String? = null, age: Int?=null): JsonModel {
val idProperty = SimpleIntegerProperty(this, "id")
var id by idProperty
val ageProperty = SimpleIntegerProperty(this, "age")
var age by ageProperty
val employeeNameProperty = SimpleStringProperty(this, "name", name)
var name by employeeNameProperty
override fun updateModel(json: JsonObject) {
with(json) {
id = int("id")!!
age = int("employee_age")!!
name = string("employee_name")
}
}
override fun toJSON(json: JsonBuilder) {
with(json) {
add("id", id)
add("employee_name", name)
add("employee_age", age)
}
}
}
class PersonEditor : View("Person Editor") {
override val root = BorderPane()
val api : Rest by inject()
var persons = listOf(Employee(1,"John", 44), Employee(2,"Jay", 33)).observable()
val model = PersonModel(Employee())
init {
api.baseURI = "https://run.mocky.io/v3/"
val response = api.get("f17509ba-2d12-4c56-b441-69ab23302e43")
println(response.list())
println(response.list().toModel<Employee>()[0].name)
// print( p.get(1))
with(root) {
center {
tableview(response.list().toModel<Employee>()) {
column("Id", Employee::idProperty)
column("Name", Employee::employeeNameProperty)
column("Age", Employee::ageProperty)
// Update the person inside the view model on selection change
model.rebindOnChange(this) { selectedPerson ->
item = selectedPerson ?: Employee()
}
}
}
right {
form {
fieldset("Edit person") {
field("Id") {
textfield(model.id)
}
field("Name") {
textfield(model.name)
}
field("Age") {
textfield(model.age)
}
button("Save") {
enableWhen(model.dirty)
action {
save()
}
}
button("Reset").action {
model.rollback()
}
}
}
}
}
}
private fun save() {
// Flush changes from the text fields into the model
model.commit()
// The edited person is contained in the model
val person = model.item
// A real application would persist the person here
println("Saving ${person.employeeNameProperty} / ${person.ageProperty}")
}
}
class PersonModel(person: Employee) : ItemViewModel<Employee>(person) {
val id = bind(Employee::idProperty)
val name = bind(Employee::employeeNameProperty)
val age = bind(Employee::ageProperty)
}
if you replace base url and send request to http://dummy.restapiexample.com/api/v1/employees you will get an error that i am talking about
Your call to mocky returns a list, so .list() works fine. Your call to restapiexample, however, returns an object, not a list, so .list() won't do what you expect. You can probably use something like this, though I haven't tested it:
response.one().getJsonArray("data").toModel<Employee>()[0].name)
Further explanation:
If you're not familiar with the structure of JSON, check out the diagrams on the JSON homepage.
TornadoFX has two convenience functions for working with JSON returns: .list() and .one(). The .list() function will check if the result is a JsonArray. If so, it simply returns it. If it is instead a JsonObject, it wraps that object in a list and returns the new list.
In your case, since restapiexample is returning an object, the result of your call to .list() is a JsonArray with a single object. It looks something like this:
[
{
"status": "success",
"data": [...]
}
]
Obviously that single object cannot be converted to an Employee, so dereferencing anything off of it will result in a NullPointerException.
The .one() function on the other hand will check if the response is a JsonObject. If it is, it simply returns the object. If, however, the response is a JsonArray, it will take the first item from the array and return that item.
I have a json file containing contact info grouped by city. I want to parse the json and create a list of names and numbers but after fiddling for an hour or so, I can't get this to work in groovy.
def json = '''{
"date":"2018-01-04T22:01:02.2125",
"boston": [
{
"name":"bob",
"phone":"242 123123",
"ext":"12",
"email":"bob#boston.com"
},
{
"name":"alice",
"phone":"212-123-345",
"ext":"1",
"email":"alice#boston.com"
}
],
"chicago": [
{
"name":"charlie",
"phone":"313-232-545",
"ext":"14",
"email":"charlie#chicago.com"
},
{
"name":"denise",
"phone":"414-123-546",
"ext":"9",
"email":"denise#chicago.com"
}
]
}'''
I have tried a few variations on the following theme but they all failed so far.
parsedjson = slurper.parseText(json)
phonelist = []
parsedjson.each{phonelist.add([it['name'],it['phone']])}
It's tricky with the json you have, as you need to look for the values which are lists... You can do this with a findAll, so given the json:
def json = '''{
"date":"2018-01-04T22:01:02.2125",
"boston": [
{
"name":"bob",
"phone":"242 123123",
"ext":"12",
"email":"bob#boston.com"
},
{
"name":"alice",
"phone":"212-123-345",
"ext":"1",
"email":"alice#boston.com"
}
],
"chicago": [
{
"name":"charlie",
"phone":"313-232-545",
"ext":"14",
"email":"charlie#chicago.com"
},
{
"name":"denise",
"phone":"414-123-546",
"ext":"9",
"email":"denise#chicago.com"
}
]
}'''
You can import the JsonSlurper and parse the json as you currently do:
import groovy.json.JsonSlurper
def parsedjson = new JsonSlurper().parseText(json)
Then;
def result = parsedjson.findAll { it.value instanceof List } // Find all entries with a list value
.values() // Get all the lists
.flatten() // Merge them into a single list
.collect { [it.name, it.phone] } // grab the name and phone for each
I'm new to groovy. I'm trying to split the values in json object in groovy but i cant seem to find a solution. Please find the sample code below
def inputFile = new File("C:\\graph.json")
def InputJSON = new JsonSlurper().parseFile(inputFile,'UTF-8')
InputJSON.each{println it}
def names = InputJSON.graph;
def name
for (int kk=0;kk<4;kk++)
{
name=names.JArray1[kk]
run.put(name.runid, name.rundetails);
println "test::"+name.runid+"--------------"+name.rundetails
}
graph.json
{
"graph": {
"JArray1": [
{
"runid": 1,
"rundetails":{
"01_Home":0.231,
"02_Login":0.561}
}
]
}
}
name.rundetails contains the below values
[01_Home:0.231, 02_Login:0.561]
I would like to split and add it as key and value in Hashmap like below format
Key:01_Home Value:0.231
Key:02_Login Value:0.561
How would i do that any advise on this would be helpful. Thanks in advance.
import groovy.json.*
def inputFile = new StringReader('''
{
"graph": {
"JArray1": [{
"runid": 1,
"rundetails": {
"01_Home": 0.231,
"02_Login": 0.561
}
}
]
}
}
''')
def json = new JsonSlurper().parse(inputFile)
json.graph.JArray1.each{run->
println "runid = ${run.runid}"
// at this point `run.rundetails` is a map like you want
println "details = ${run.rundetails}"
}
As I understand you need collection like:
[[Key:01_Home, Value:0.231], [Key:02_Login, Value:0.561]]
Then you may do:
println InputJSON.graph
.JArray1
.rundetails
.collectEntries{it}
.collect{[Key: it.key, Value: it.value]}
I have the following JSON code:
{
"TIMESTAMP":"2017-05-26-20.22.40.016000",
"dateTime":"2017-05-26H-20.22.4",
"AMUCCY1":"ADP",
"rates":[
{
"AMUCCY2":"AED",
"AMURAT":"1.000000000",
"AMUNXRT":0
},
{
"AMUCCY2":"AFA",
"AMURAT":"1.000000000",
"AMUNXRT":0
},
{
"AMUCCY2":"ALL",
"AMURAT":"1.000000000",
"AMUNXRT":0
},
{
"AMUCCY2":"AMD",
"AMURAT":"1.000000000",
"AMUNXRT":0
}
]
}
Is there quick way in groovy where I could loop through each of the 'rates' and get the value of, let's say 'AMUCCY2' ?
I tried doing this code:
jsonObj.rates.each {
def toCurrencyMap = jsonObj.rates.AMUCCY2
LOG.info "${toCurrencyMap}"
}
but the toCurrencyMap returns an array of all four values of this field. I only want to get each value; not all.
Any suggestions is appreciated.
You can try this:
jsonObj.rates.each {
println it.AMUCCY2
}
If you want list / array:
def result = jsonObj.rates.collect { it.AMUCCY2 }
println result