Parsing Groovy Json Into Key Value - json

I'm attempting to parse Json using Groovy's jsonslurper. I'd like to drill down into the "id" and "label" elements and create a key:value pair from them. This is my attempt:
def slurper = new groovy.json.JsonSlurper()
def json = slurper.parseText(myjson)
result = [:]
json.each {
result.put(json.menu.items.id,json.menu.items.label)
}
println result
​
What I expect is a result of:
[ [Open, null], [OpenNew, Open New], [Zoomin, Zoom In], etc....]
What I get is one list of the id's and one list of the labels. Any suggestion on how to get the desired result? Here is the Json I'm feeding...
{
"menu":{
"header":"SVG Viewer",
"items":[
{
"id":"Open"
},
{
"id":"OpenNew",
"label":"Open New"
},
null,
{
"id":"ZoomIn",
"label":"Zoom In"
},
{
"id":"ZoomOut",
"label":"Zoom Out"
},
{
"id":"OriginalView",
"label":"Original View"
},
null,
{
"id":"Quality"
},
{
"id":"Pause"
},
{
"id":"Mute"
},
null,
{
"id":"Find",
"label":"Find..."
},
{
"id":"FindAgain",
"label":"Find Again"
},
{
"id":"Copy"
},
{
"id":"CopyAgain",
"label":"Copy Again"
},
{
"id":"CopySVG",
"label":"Copy SVG"
},
{
"id":"ViewSVG",
"label":"View SVG"
},
{
"id":"ViewSource",
"label":"View Source"
},
{
"id":"SaveAs",
"label":"Save As"
},
null,
{
"id":"Help"
},
{
"id":"About",
"label":"About Adobe CVG Viewer..."
}
]
}
}

You can do this
def result = new JsonSlurper()
.parseText(json)
.menu
.items
.findAll() // Throw away the 4 `null` ones
.collect { [ it.id, it.label ] }

Related

How to do custom window function on JSON object with pandas?

I have a rather nested JSON object below, and I am trying to calculate the user (ie 'profileId') with the most events (ie length of 'parameters' key.
I have the code below to get the length of the parameter, but I am trying to now have that calculation be correct for each record, as they way I have it set now would set it the same value for each record - I looked into pandas window functions https://pandas.pydata.org/docs/user_guide/window.html but am having trouble getting to the correct outcome.
response = response.json()
df = pd.json_normalize(response['items'])
df['calcfield'] = len(df["events"].iloc[0][0].get('parameters'))
the output of df['arrayfield'] is below:
[
{
"type":"auth",
"name":"activity",
"parameters":[
{
"name":"api_name",
"value":"admin"
},
{
"name":"method_name",
"value":"directory.users.list"
},
{
"name":"client_id",
"value":"722230783769-dsta4bi9fkom72qcu0t34aj3qpcoqloq.apps.googleusercontent.com"
},
{
"name":"num_response_bytes",
"intValue":"7158"
},
{
"name":"product_bucket",
"value":"GSUITE_ADMIN"
},
{
"name":"app_name",
"value":"Untitled project"
},
{
"name":"client_type",
"value":"WEB"
}
]
}
] }, {
"kind":"admin#reports#activity",
"id":{
"time":"2022-05-05T23:58:48.914Z",
"uniqueQualifier":"-4002873813067783265",
"applicationName":"token",
"customerId":"C02f6wppb"
},
"etag":"\"5T53xK7dpLei95RNoKZd9uz5Xb8LJpBJb72fi2HaNYM/9DTdB8t7uixvUbjo4LUEg53_gf0\"",
"actor":{
"email":"nancy.admin#hyenacapital.net",
"profileId":"100230688039070881323"
},
"ipAddress":"54.80.168.30",
"events":[
{
"type":"auth",
"name":"activity",
"parameters":[
{
"name":"api_name",
"value":"gmail"
},
{
"name":"method_name",
"value":"gmail.users.messages.list"
},
{
"name":"client_id",
"value":"927538837578.apps.googleusercontent.com"
},
{
"name":"num_response_bytes",
"intValue":"2"
},
{
"name":"product_bucket",
"value":"GMAIL"
},
{
"name":"app_name",
"value":"Zapier"
},
{
"name":"client_type",
"value":"WEB"
}
]
ORIGINAL JSON BLOB I READ IN
{
"kind":"admin#reports#activities",
"etag":"\"5g8\"",
"nextPageToken":"A:1651795128914034:-4002873813067783265:151219070090:C02f6wppb",
"items":[
{
"kind":"admin#reports#activity",
"id":{
"time":"2022-05-05T23:59:39.421Z",
"uniqueQualifier":"5526793068617678141",
"applicationName":"token",
"customerId":"cds"
},
"etag":"\"jkYcURYoi8\"",
"actor":{
"email":"blah#blah.net",
"profileId":"1323"
},
"ipAddress":"107.178.193.87",
"events":[
{
"type":"auth",
"name":"activity",
"parameters":[
{
"name":"api_name",
"value":"admin"
},
{
"name":"method_name",
"value":"directory.users.list"
},
{
"name":"client_id",
"value":"722230783769-dsta4bi9fkom72qcu0t34aj3qpcoqloq.apps.googleusercontent.com"
},
{
"name":"num_response_bytes",
"intValue":"7158"
},
{
"name":"product_bucket",
"value":"GSUITE_ADMIN"
},
{
"name":"app_name",
"value":"Untitled project"
},
{
"name":"client_type",
"value":"WEB"
}
]
}
]
},
{
"kind":"admin#reports#activity",
"id":{
"time":"2022-05-05T23:58:48.914Z",
"uniqueQualifier":"-4002873813067783265",
"applicationName":"token",
"customerId":"df"
},
"etag":"\"5T53xK7dpLei95RNoKZd9uz5Xb8LJpBJb72fi2HaNYM/9DTdB8t7uixvUbjo4LUEg53_gf0\"",
"actor":{
"email":"blah.blah#bebe.net",
"profileId":"1324"
},
"ipAddress":"54.80.168.30",
"events":[
{
"type":"auth",
"name":"activity",
"parameters":[
{
"name":"api_name",
"value":"gmail"
},
{
"name":"method_name",
"value":"gmail.users.messages.list"
},
{
"name":"client_id",
"value":"927538837578.apps.googleusercontent.com"
},
{
"name":"num_response_bytes",
"intValue":"2"
},
{
"name":"product_bucket",
"value":"GMAIL"
},
{
"name":"client_type",
"value":"WEB"
}
]
}
]
}
]
}
Use:
df.groupby('actor.profileId')['events'].apply(lambda x: [len(x.iloc[i][0]['parameters']) for i in range(len(x))])
which returns the list of each profileid count of parameters. Output and the sample data:
actor.profileId
1323 [7]
1324 [7]
Name: events, dtype: object
It's not entirely clear what you asking and df['arrayfield'] isn't in your example provided. However, if you look at the events column after json_normalize, you can use the following line to pull out the length of each parameters key. The blob you gave as an example was set to response...
df = pd.json_normalize(response['items'])
df['calcfield'] = df['events'].str[0].str.get('parameters').str.len()
Becauase each parameters key has 7 elements, it's tough to say this is what you really want.

convert JavaScript nested array for priming tree format

i have following JAVASCRIPT OBJECT and i need to convert it to primeng tree format , please help
INPUT
{
"com": {
"ups": {
"demo": {
"a": 9
}
}
}
}
OUTPUT expected
[
{
"label": "COM",
"data": "COM",
"children": [{
"label": "ABC",
"data": "abc",
"children": [ "label": "x" data": "x" ,children:[]]
}]
}]
Working Example
validate(a) {
let newArr = [];
for (const key in a) {
if (key) {
newArr.push({data: key, label: key, childern: this.validate(a[key])});
}
}
return newArr;
}
const a = {
"com": {
"ups": {
"demo": {
"a": 9
}
}
}
};
console.log(this.validate(a));

How to update a key value in JSON dynamically?

I have a JSON like below
{
"context":{
"parameters":[
{
"name":"stub",``
"value": {"item value":"abcdefg"}
},
{
"name":"category",
"value":{"item value":"cars"}
},
{
"name":"year",
"value":{"item value":"2012"}
},
{
"name":"make",
"value":{"item value":"toyota"}
},
{
"name":"cars",
"value":{"item value":"corolla"}
}
]
}
I am supplied with a two strings dynamically like "cars" and "accord". I need to search for "cars" and then replace the "item value" under it to "accord". I have tried to convert it to map but have no success.
Any suggestions about how I can achieve this?
Here's one way to do it in Groovy.
Assuming that the JSON is like so (I have corrected it; there are illegal chars in the original question):
def s = '''
{
"context":{
"parameters":[
{
"name":"stub",
"value": {"item value":"abcdefg"}
},
{
"name":"category",
"value":{"item value":"cars"}
},
{
"name":"year",
"value":{"item value":"2012"}
},
{
"name":"make",
"value":{"item value":"toyota"}
},
{
"name":"cars",
"value":{"item value":"corolla"}
}
]
}
}
'''
then consider:
import groovy.json.*
def jsonSlurper = new JsonSlurper().parseText(s)
def category = jsonSlurper.context.parameters.find { it.name == "cars" }
category.value."item value" = "accord"
println new JsonBuilder(jsonSlurper).toPrettyString()
you can do that with javascript. If you are working with JSON format you can parse that data to an object.
const data = JSON.parse("your json data")
data.context.parameters.map(param => {
if ( param.name !== "cars") {
return param
}
return {
"name": "cars",
value: {"accord": "corolla"}
}
})

Append json into a json in groovy

I am newbie to groovy. My requirement is i have to append a json into a json.My code as follows:
JSON constructed by me:
def builder = new groovy.json.JsonBuilder()
def root=builder.event{
type "model_output_load_init"
time new Timestamp(date.getTime())
status "success"
}
JSON from DB:
def json = rs.getString("status");
Now i have to append constructed into the JSON From DB. PLease help me to solve this.Thanks in advance.
EDIT:
My Constructed JSON:
{
"event": {
"type": "model_output_load_init",
"time": "2015-10-01T14:08:17+0000",
"status": "success"
}
}
JSON FROM DB:
{
"model_build": {
"Initialized": {
"Timestamp": ""
}
},
"modelExec": {
"Initialized": {
"Timestamp": ""
}
}
}
OUTPUT NEEDED:
{
"model_build": {
"Initialized": {
"Timestamp": ""
}
},
"modelExec": {
"Initialized": {
"Timestamp": ""
}
},
"event": {
"type": "model_output_load_init",
"time": "2015-10-01T14:08:17+0000",
"status": "success"
}
}
You can append to the Map generated by JsonSlurper.
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def builder = new JsonBuilder()
def root = builder.event{
type "model_output_load_init"
time new Timestamp(date.getTime())
status "success"
}
// Simulates the JSON from DB
def json = new JsonSlurper().parseText('''
{
"model_build": {
"Initialized": {
"Timestamp": ""
}
},
"modelExec": {
"Initialized": {
"Timestamp": ""
}
}
}''')
// Append the built JSON to the "slurped" JSON
json.event = root.event
// Re-build the JSON so it can saved as a String
new JsonBuilder(json).toPrettyString()
The output looks like this:
{
"event": {
"type": "model_output_load_init",
"time": "2015-10-01T14:39:11+0000",
"status": "success"
},
"modelExec": {
"Initialized": {
"Timestamp": ""
}
},
"model_build": {
"Initialized": {
"Timestamp": ""
}
}
}

Groovy JsonBuilder array of objects

I have a JsonBuilder that I'm having some trouble with. I'd like the output to look like the following:
"unitTests": {
"testType": "TestNG",
"totalTests": 20,
"failedTests": 2,
"skippedTests": 0,
"failedTestList": [
{
"class": "SomeTestClass"
"method": "someTestMethod"
},
{
"class": "AnotherTestClass"
"method": "anotherTestMethod"
}
]
}
Instead what I am seeing is:
"unitTests": {
"testType": "TestNG",
"totalTests": 20,
"failedTests": 2,
"skippedTests": 0,
"failedTestList": [
[
{
"class": "SomeTestClass"
}
],
[
{
"method": "someTestMethod"
}
],
[
{
"class": "AnotherTestClass"
}
],
[
{
"method": "anotherTestMethod"
}
]
]
}
The code to generate the JSON document is below:
def json = new JsonBuilder()
def root = json {
time { $date timestamp }
data {
unitTests {
testType unitType
totalTests totalUnitTests
failedTests failedUnitTests
skippedTests skippedUnitTests
failedTestList(failedUnitTestClass.collect {[class: it]}, failedUnitTestMethod.collect {[method: it]})
}
}
}
There's a need to iterate both lists at the same time. Try:
[failedUnitTestClass, failedUnitTestMethod].transpose().collect { [class:it[0], method:it[1]] }
Full example:
import groovy.json.*
def json = new JsonBuilder()
def failedUnitTestClass = ['cls1', 'cls2', ]
def failedUnitTestMethod = ['m1', 'm2', ]
json.unitTests {
failedTestList([failedUnitTestClass, failedUnitTestMethod].transpose().collect {[class:it[0], method:it[1]]})
}
println JsonOutput.prettyPrint(json.toString())