Get value of variable from json using jsonslurper - json

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

Related

How to get an image url in this json file in flutter

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

Newtonsoft.json SelectToken Replace differs from SelectTokens Replace in foreach with a NullReferenceException

Hope anybody could guide me here. I spend some hours on it and can't understand what's going on.
Mission: Replace a json element by a jsonpath search tag. (sort of $ref feature)
In my code example below i want to replace the value of DataReaderUser by a value found by the json path search $.UsersAndGroups.Users[?(#.Name == 'OMDASAccountUser')].Username . In this case it should result in the value "contoso\SVCSCOM-DO-OMDAS"
The code below works as expected.. the issue is below this code ..
https://dotnetfiddle.net/gEjggK
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = #"{
""SQLServer"": {
""SQLReportingServices"": {
""AccountSettings"": {
""DataReaderUser"": {""$JsonPath"": ""$.UsersAndGroups.Users[?(#.Name == 'OMDASAccountUser')].Username""},
}
}
},
""UsersAndGroups"": {
""Users"": [
{
""Name"": ""OMActionAccountUser"",
""Username"": ""contoso\\SVCSCOM-DO-OMDAS"",
},
{
""Name"": ""OMDASAccountUser"",
""Username"": ""contoso\\SVCSCOM-DO-OMDAS"",
}
]
}
}";
JObject jo = JObject.Parse(json);
var JsonPath = jo.SelectToken("..$JsonPath");
JsonPath.Parent.Parent.Replace(jo.SelectToken(JsonPath.ToString()));
Console.WriteLine(jo.ToString());
}
}
The output will be :
{
"SQLServer": {
"SQLReportingServices": {
"AccountSettings": {
"DataReaderUser": "contoso\\SVCSCOM-DO-OMDAS"
}
}
},
"UsersAndGroups": {
"Users": [
{
"Name": "OMActionAccountUser",
"Username": "contoso\\SVCSCOM-DO-OMDAS"
},
{
"Name": "OMDASAccountUser",
"Username": "contoso\\SVCSCOM-DO-OMDAS"
}
]
}
}
Now the issue:
I want to do the same for all possible jsonpaths refers. So i use the SelectTokens and an foreach . But it looks like the behavior is different , the parents are null.
https://dotnetfiddle.net/lZW3XP
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = #"{
""SQLServer"": {
""SQLReportingServices"": {
""AccountSettings"": {
""DataReaderUser"": {""$JsonPath"": ""$.UsersAndGroups.Users[?(#.Name == 'OMDASAccountUser')].Username""},
}
}
},
""UsersAndGroups"": {
""Users"": [
{
""Name"": ""OMActionAccountUser"",
""Username"": ""contoso\\SVCSCOM-DO-OMDAS"",
},
{
""Name"": ""OMDASAccountUser"",
""Username"": ""contoso\\SVCSCOM-DO-OMDAS"",
}
]
}
}";
JObject jo = JObject.Parse(json);
var JsonPaths = jo.SelectTokens("..$JsonPath");
foreach (var JsonPath in JsonPaths )
{
JsonPath.Parent.Parent.Replace(jo.SelectToken(JsonPath.ToString()));
}
Console.WriteLine(jo.ToString());
}
}
And the output:
Run-time exception (line 34): Object reference not set to an instance of an object.
Stack Trace:
[System.NullReferenceException: Object reference not set to an instance of an object.]
at Newtonsoft.Json.Linq.JsonPath.PathFilter.GetNextScanValue(JToken originalParent, JToken container, JToken value)
at Newtonsoft.Json.Linq.JsonPath.ScanFilter.<ExecuteFilter>d__4.MoveNext()
at Program.Main() :line 34
would be great to get some directions since i am spinning my head here.
michel
SelectTokens uses lazy evaluation and if you modify the token while enumerating all matches it can break in unexpected ways. A simple fix is to add ToArray() to force eager evaluation:
var JsonPaths = jo.SelectTokens("..$JsonPath").ToArray();

Unable to split the values in jsonobject in groovy

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]}

JSON : Accessing (editing) value using dynamic key

I have a JSON Object which looks like :
{ "stepbystep": { "steps": { },
"step1": "This is a step"
}
}
I need to edit the value of "step1" using a function.
My function is
function editJSON(parsedJSON,key) // parsedJSON is the JSONObject,key = "stepbystep.step1"
{
parsedJSON[key] = "This is now step 1";
}
How do I access inner/deep values using dynamic keys ?
Access your json like this :
// $js has json
$response = json_decode($js,true);
$stepbystep=$response["stepbystep"];
foreach($stepbystep_arr AS $stepbystep_obj)
{
echo $stepbystep_obj['step1'];// here is your desired value
//if you want dynamic step1, step2... you can use for loop
//$n is count
for($i=1;$i<=$n;$i++)
{
$stepbystep_obj['step'.$i];
}
}

Groovy to create JSON

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)
}