Mule- Mapping key and values to new keys and values - json

I need to extract key and values from json to form different json output
Input Json
{"somekey":"xyz",
"properties":{
"key1":"value1",
"key2":"value2"
.....
}
Expected Output Json
{"somekey":"xyz",
"properties":{
"mainkey1": "value1"
"mainkey2": "value2"
....
}
}
I need to add "main" to the existing key and read all the keys. Consider there's n number of key value pairs in properties.
How can this be done dwl script?
I tried to map the objects using payload map and write manually the entire keys. As new key value pairs get added i had to write each keys manually into mapping.

You can use update operator to update the parent object. Update will keep the existing keys and only update the props object. To concatenate the property keys a mapObject can be used.
%dw 2.0
output application/json
---
payload update {
case props at .properties -> props mapObject ((value, key) -> {
("main" ++ (key as String)): value
})
}

Related

JSONPath Expression to return objects within an array based on value of a key

I have a JSON Array which contains multiple JSON objects:
[
{
"s3_uri":"s3://fake-s3-bucket/fact_table/fact_table.csv",
"dataset":"fact_table"
},
{
"s3_uri":"s3://fake-s3-bucket/dimension_table/dimension_table.csv",
"dataset":"dimension_table"
}
]
I would like to filter the JSON using a JSONPath Expression based on the "dataset" key value of "dimension_table" and return all the objects in the array which match this search criteria.
This is the desired filter result.
[
{
"s3_uri":"s3://fake-s3-bucket/dimension_table/dimension_table.csv",
"dataset":"dimension_table"
}
]
I have attempted to use a filter $[*][?(#.dataset==dimension table)] but this does not maintain the structure of the object and we lose the keys of the object:
[
"s3://fake-s3-bucket/dimension_table/dimension_table.csv",
"dimension_table"
]
Is this possible to achieve with a JSONPath Expression?
The following works on https://jsonpath.com:
$[?(#.dataset=='dimension_table')]

Get multiple JSON keypair values within a JSON object only if a specific keypair value matches iterable

I am trying to pull multiple json keyvalue data within any given JSON object, from a JSON file produced via an API call, for only the JSON objects that contain a specific value within a keyvalue pair; this specific value within a keyvalue pair is obtained via iterating through a list. Hard to articulate, so let me show you:
Here is a list (fake list representing my real list) I have containing the "specific value within a keyvalue pair" I'm interested in:
mylist = ['device1', 'device2', 'device3']
And here is the json file (significantly abridged, obviously) that I am reading from my python script:
[
{
"name": "device12345",
"type": "other",
"os_name": "Microsoft Windows 10 Enterprise",
"os_version": null
},
{
"name": "device2",
"type": "other",
"os_name": "Linux",
"os_version": null
},
{
"name": "device67890",
"type": "virtual",
"os_name": "Microsoft Windows Server 2012 R2 Standard",
"os_version": null
}
]
I want to iterate through mylist, and for each item in mylist that matches the json keyvalue key "name" in the json file, print the values for 'name' and 'os_name'. In this case, I should see a result where after iterating through mylist, device2 matches the 'name' key in the json object that contains {'name':'device2'}, and then prints BOTH the 'name' value ('device2') and the 'os_name' value ('Linux'), and then continues iterating through mylist for the next value to iterate through the json file.
My code that does not work; let us assume the json file was opened correctly in python and is defined as my_json_file with type List:
for i in mylist:
for key in my_json_file:
if key == i:
deviceName = i.get('name')
deviceOS = i.get('os_name')
print(deviceName)
print(deviceOS)
I think the problem here is that I can't figure out how to "identify" json objects that "match" items from mylist, since the json objects are "flat" (i.e. 'device2' in my json file doesn't have 'name' and 'os_name' nested under it, which would allow me to dict.get('device2') and then retrieve nested data).
Sorry if I did not understand your question clearly, but it appears you're trying to read values off of the list instead of the JSON file since you're looking at i.get instead of key.get when key is what actually contains the information.
And for the optimization issue, I'd recommend converting your list of devices into a set. You can then iterate through the JSON array and check if a given name is in the set instead of doing it the other way. The advantage is that sets can return if they contain an item in O(1) time, meaning it will significantly speed up the overall speed of the program to O(n) where n = size of json array.
for key in my_json_file:
if key.get('name') in my_list:
deviceName = key.get('name')
deviceOS = key.get('os_name')
print(deviceName)
print(deviceOS)

Dart How To parse JSON With Unique Key, Value Pairs

I am parsing a JSON object containing several key value pairs but am not sure how to make objects out of the JSON below. The keys are always different depending on the GET request so I am not able to use json['keyname'] like usual. What kind of function would I need in order to return a list of keys from 'ccwms' and a respective list of values (floats)?
{
"ccwms": {
"frc118": 160.8076758518209,
"frc1255": 15.257951313413884,
"frc1296": 11.42077882954301,
"frc7321": -161.58464745359254
}
}
After parsing the JSON, you have a normal Dart Map with string keys and some values. You can iterate maps in several ways, for example:
for (var key in map.keys) { doSomething(key, map[key]); }
for (var entry in map.entries) { doSomething(entry.key, entry.value); }
map.forEach(doSomething);
(Map.keys, Map.entries, Map.forEach).
I'm sure there are more ways to access all the keys and values.
What you do with the keys and values is up to you, it's just a map.
Minimal Dart program to convert a json string:
import 'dart:convert';
main() {
String source = """{"X":"RRRR","Y":"SSSS","ccwms": {
"frc118": 160.8076758518209,
"frc1255": 15.257951313413884,
"frc1296": 11.42077882954301,
"frc7321": -161.58464745359254
}}""";
dynamic target = JsonDecoder().convert(source);
print ( source.toString());
}
Are these keys random ? I think keys have to be predefined set, because json is a serialization for already existed object and the object structure can not be random
hope I understand correctly
should be a comment but I can not add comments right now.

iterate json object data using map along with key

I have trying to get collection of data from json object using map and assign key, pair reference in loop but its not working out for me. I can read value in iterations but I need to assign to key and value where I need help. its not recognising "key" and "value"
var j1 = _preDefineAnswerOptions.map(function(item){
return ["key": item.preDefineAnswerId, "value": item.text];
});
data-source structure
You need to return an object. Use {} around the key and value.
var j1 = _preDefineAnswerOptions.map(function(item){
return {"key": item.preDefineAnswerId, "value": item.text};
});

how to parse inner level json objects if the keys are unknown in groovy

i am doing an automation script in which i m getting inner levels json and the keys are unknown to me so how can we parse the json so that it convert the json into a map with key value pairs it contains the json array as well as json object i want to create them separately so that we can distinguish b/w these.
i m having a json format as-:
{
"seatbid":[
{
"bid":[
{
"id":"1",
"impid":"1",
"price":3.5999999046325684,
"nurl":"abc.com",
"adomain":[
"zagg.com",
"zagg.com"
],
"iurl":"abc.com",
"crid":"30364.s320x50m",
"h":0,
"w":0
}
],
"group":0
}
],
"cur":"USD",
"nbr":0
}
my code is as follows but its not working at all because the key values i have to enter to get the values -:
def respSlurper = new JsonSlurper()
def respJson = respSlurper.parseText(content)
log.info(respJson.keySet())
log.info(respJson.values())
log.info(respJson.get("seatbid"))`