I am using Anypoint Studio 6.1 and Mule 3.8.1 and am mapping JSON to JSON in Dataweave. In the JSON mapping I have an optional field called "Channels" which contains a list of strings. When the field is not there I get a warning in Dataweave. How can I write the Dataweave code to ignore if its null?
Dataweave code:
%dw 1.0
%output application/json skipNullOn="everywhere"
---
payload map ((payload01 , indexOfPayload01) -> {
Channels: payload01.Channels map ((channel , indexOfAccessChannel) -> channel)
})
I have tried to use "when" and also the "?" selector modifier but cannot get the syntax right.
Thanks
You were right to use when and the ? operator. You just need to use parentheses to make sure they apply to the right things. Note that I am using $ as a shorthand for the payload01 parameter in your example.
%dw 1.0
%output application/json
---
payload map {
(Channels: $.Channels map (lower $)) when $.Channels?
}
If you didn't need to use map on the Channels array within each item, you could just allow the null to pass through:
payload map {
Channels: $.Channels
}
This would yield the following for input objects that don't contain a Channels field:
{
Channels: null
}
Adding the parentheses allows us to use when to determine whether the whole key/value pair (aka tuple) should be output:
payload map {
(Channels: $.Channels) when $.Channels?
}
Yielding:
{
}
Related
I have a json response as,
{
'sadasd123242' : 'asdadada122dfsfs',
'dadsadaskljk' : 'adasdasdasdsadds'
}
I want to extract the keys from the response in jmeter test using the JSON extractor. I am unable to do this as I do not know the keys in the response. How do I get the keys ?
Assuming you have the response in the following format:
{
"data": {
"assets": {
"sadsad12dwqqwe": "asda1212312",
"asdasd1213123": "asdas2131231"
}
}
}
You can extract key names using JSR223 PostProcessor and the following code:
new groovy.json.JsonSlurper().parse(prev.getResponseData()).data.assets.eachWithIndex{ def node, int idx ->
log.info('Key ' + idx + '=' + node.getKey())
vars.put('key_' + idx, node.getKey())
}
It will print key names into jmeter.log file and create JMeter Variables like:
- `${key_1}`
- `${key_2}`
- etc.
holding the required "key" values.
Demo:
References:
Apache Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
Considering first value as key which is dynamic and second value you have to fetch.
You can use "Boundary extractor" post processor in that case by defining the left and right boundary as shown in the below image.
Check the below test for boundary expression to get the desired result:-
Hope this help.
This is probably simple, but everything I find in a search is only vaguely related to my question.
I have this:
{
"user":"C03999",
"caseNumber":"011-1234567",
"documents":[
{
"file":[
{"name":"indem1","document":"xSFSF%%GSF","mimeType":"PDF"},
{"name":"indem2","document":"xSFSF%%GSF","mimeType":"PDF"}
]
}
],
"mortgagee":"22995",
"billTo":"Originator",
"agreementDate":"2016-11-25",
"term":360,
"expirationDate":"2017-11-25",
"startDate":"Agreement",
"lenderEndorsed":true,
"lenderExecutedAgreement":false,
"indemnificationAgreementTransferable":false,
"qadLrsFileNumber":"2016-99999-9999",
"docketNumber":"2016-9999-99"
}
I would like to get this string out of it:
indem1,indem2
I created a global function:
<configuration doc:name="Configuration">
<expression-language autoResolveVariables="true">
<global-functions>
def convertToString(data){
return data.toString();
}
</global-functions>
</expression-language>
</configuration>
My transform looks like this:
%dw 1.0
%output application/csv
---
payload.documents.file map {
"" : convertToString($.name)
}
My output looks like:
[indem1\, indem2]
What do I need to do to get my desired string (indem1,indem2)?
Your question title says that " JSON array To string" but the dataweave code attached above has application/csv in the output.
Are you trying to convert into csv?? If that is the expectation, comma is a reserved character for .csv format and that is the reason , is getting escaped with backslash[indem1\,indem2].
If your intention is to convert into java, here is the code that returns String value.
%dw 1.0
%output application/java
payload.documents[0].file.*name joinBy ','
In general, if you have an object, and you need PART of that object to be written in a given format / MIME-type, use the write() function in the dw::Core module. If you need to read some content in an object that is JSON/JAVA/CSV and the rest is some other format, use the read() function in the same module.
For example, suppose you have payload as:
{
field1: "foo",
field2: { nested: "value" }
}
Further, suppose that you want the object to be JAVA, but the "field2" value to be seen as JSON. You can use this DW:
output application/java
---
{
field1: payload.field1,
field2: write(payload.field2,'application/json')
}
The result is:
{
field1: "foo",
field2: '{ "nested": "value" }'
}
NOTICE that "field2" now shows up as a nested JSON object, not a JAVA object. One way to tell is that the key in the JSON object is in quotes, but in a JAVA object they are not.
I have a CSV like this:
data1,data2,data3;dataa;datab;datac;datax,datay,dataz
data1,data2,data3;dataa;datab;datac;datax,datay,dataz
data1,data2,data3;dataa;datab;datac;datax,datay,dataz
I use spliter to process the records line by line, further I use splitBy "," in dataweave to convert the record to a map. But how I can do another level of split for ";" ? SplitBy doesnt allow muliple delimiters so do the CSV type in dataweave.
Ultimately, I want a JSON like this:
{
"1":"data1",
"2":"data2",
"3":{
"a":"dataa",
"b":"datab",
"c":"datac"
},
"x":"datax",
"y":"datay",
"z":"dataz "
}
Any thoughts ?
Try the following DataWeave code:
%dw 1.0
%output application/json
---
payload map {
"1": $[0],
"2": $[1],
"3": using (detail = $[2] splitBy ";") {
a: detail[1],
b: detail[2],
c: detail[3]
},
x: $[3],
y: $[4],
z: $[5]
}
Notes:
I modified the input data to separate datac and datax. Replace the ; character with , e.g.: ...;datab;datac,datax,...
I use File connector to read the CSV file, and directly process it in DataWeave transformer (do not use a Splitter)
I want to observe, that your JSON example has bad structure!
In this JSON the 4th element is an object and it hasn't a key, just value...
First of all, u should validate your end JSON.
Example of your valid JSON:
When u validate your JSON, I'll try to help in convering your CSV data to the JSON.
I want to extract the first key from the json response, which should be passed as an input for next HTTP request in Jmeter.
This is my input (javascript object):
Object({"details": { "key1": {"s_1": "s_v", "s_2": "s_v" }, "key2": {"s_1": "s_v", "s_2": "s_v" } }})
I need to get "key1" in a variable.
Try "JSON Path PostProcessor" in Post Processors and the expression may be "$..key1".
Add Regular Expression Extractor as a child of the request which returns the above response.
Configure the Regular Expression Extractor as follows:
Reference Name: anything meaningful, i.e. key_1
Regular Expression: "key1": {(.+?)}
Template: $1$
Refer the extracted value as ${key_1} where required
You can test your Regular Expressions using "RegeExp Tester" mode of the View Results Tree listener
Demo:
References:
Regular Expressions
Using RegEx (Regular Expression Extractor) With JMeter
Perl5 Regex Cheat Sheet
what's the simplest way to respond in json using grails?
E.G. the following doesn't work.
boolean a = false
render a as JSON
Grails requires that the target of the JSON converter be something that can be represented as a collection of name/value pairs or an ordered list. So an object such as a map or list would work. And non-primitive objects should also work, since they can be represented as a map of properties.
In your case, something like this would work:
def a = []
a << false
render a as JSON
directly from the documentation, something like
render(contentType: "text/json") {
hello = "world"
}
render(contentType: "application/json"){
message{
a.each{val->
value(val)
}
}
}
Use grails.converter.JSON and you can build the json map directly
http://manbuildswebsite.com/2010/02/08/rendering-json-in-grails-part-2-plain-old-groovy-objects-and-domain-objects/