how to write data weave code for given input and output - mulesoft

I want to reduce or replace this [] with {}
input: ["abcd,"whyf","thsr"]
output: {"abcd,"whyf","thsr"}

Assuming the input is in JSON it means it is an array. It could be just a string too. The output is not a valid JSON document, because starting with a curly brackets it means it should be an object, but it misses keys for each value.
If for some reason you are intending to just output a string with the square brackets replaced with the curly brackets, then you can transform the input as a string and then use string replaces to change the characters, but be aware that the output is not valid JSON, nor any other supported structured format.
%dw 2.0
output application/java
---
write(payload,"application/json",{indent:false}) replace /\[/ with("{") replace /]/ with("}")
Output (as a string):
{"abcd","whyf","thsr"}

Assuming the output to be string you can also try the following which uses joinBy
%dw 2.0
output text/plain
---
'{"' ++ (payload joinBy '","') ++ '"}'

Related

Jq Convert multiple string inputs to one larger array without slurp or inputs

I have:
Filter:
["key:\(.key)", "value:\(.value)"][]
Input:
{"key":"state","value":"pending"}
{"key":"options","value":"request"}
Output:
"key:state"
"value:pending"
"key:options"
"value:request"
Demo
https://jqplay.org/s/9yq89orzL0
I want to convert the output "key:state" "value:pending" "key:options" "value:request" to array ["key:state", "value:pending", "key:options", "value:request"].
I tried reduce . as $s ([]; .+[$s]) but this gives ["key:state"] ["value:pending"] ["key:options"] ["value:request"].
I want a solution without using slurp or inputs.
Thanks.
I want a solution without using slurp or inputs.
Unfortunately, unless you’re willing to invoke jq twice, those are the only two options that jq has to offer, unless you allow input. And the same can be said of gojq and jaq.
If your input is JSONL (one JSON per line), then there are of course many obvious ways to preprocess the stream to achieve the "slurping" effect. Otherwise, you'd probably want to use a JSON-oriented tool, either to supplement jq, or to use instead.
If you can use --null-input and input :
#!/usr/bin/env bash
jq --null-input '
def loop:
.+(input|["key:\(.key)", "value:\(.value)"]) |
. as $res |
try loop catch $res ;
loop
' << EOF
{"key":"state","value":"pending"}
{"key":"options","value":"request"}
EOF
output:
[
"key:state",
"value:pending",
"key:options",
"value:request"
]
I wouldn't consider this a very practical solution but you could switch the scope from the itemwise stream to an enveloping singleton by using a second call to jq, and an appropriate encoding for the transition, thus using -j and -R to write and read a single line of raw text. Technically, this fulfills your requirements (not using slurp or inputs), but is it worth it?
One such way could be to manually build a JSON array from already JSON-encoded parts by adding commas and brackets:
In the first instance, encode the items as JSON using tojson, and append a comma to each. In the second instance, remove the last character (the superfluous comma), wrap the string in brackets, and decode the ready JSON array using fromjson.
jq -j '"key:\(.key)", "value:\(.value)" | "\(tojson),"' | jq -R '"[\(.[:-1])]" | fromjson'
[
"key:state",
"value:pending",
"key:options",
"value:request"
]
Just an elaboration on Philippe's answer.
Demo
https://jqplay.org/s/C_C-xudpVQ
Filter
def to_array: .+[input] | . as $acc | try to_array catch $acc; to_array
Input
"foo is bar"
"goo is google"
"stack is over"
"over is flow"
Output
[
"foo is bar",
"goo is google",
"stack is over",
"over is flow"
]
In to_array function, on each iteration we add an input to a single array and save to $acc (aka 'accumulated') , until there is no more input, in which case we output the $acc up to that point (since try will fail in that case this will execute catch exp).

How to get a valid strings array in JSON format?

I have and string array in json format as follows, which I will be adding to my API header
[\"Authorization:\ Basic\ T1BFTlZJRFVBUFA6UmVzcG9uc2VARXllITIz\"]
But I get the below error when I try to restart my server which has the above property set in .env file
Property OPENVIDU_WEBHOOK_HEADERS=[\"Authorization:\ Basic
T1BFTlZJRFVBUFA6UmVzcG9uc2VARXllITIz\"]. Is not a valid strings array
in JSON format. com.google.gson.stream.MalformedJsonException:
Expected value at line 1 column 2 path $[0]
What would be the correct way to define the property?
It is to do with the escaping of your string.
Correct String :
["Authorization: \"Basic T1BFTlZJRFVBUFA6UmVzcG9uc2VARXllITIz\""]

Dataweave - Array of Objects to Object per line

My input is an Array of Java Objects:
[{"name"="Demo","platform"=[{"id"="1","value"="ios"},{"id"="2","value"="android"}],"language"=[{"id"="1","value"="eng"}],"date"="20/05/2018"}, {"name"="Kernel","platform"=[{"id"="1","value"="macos"},{"id"="2","value"="linux"}],"language"=[{"id"="1","value"="ger"}],"date"="20/05/2018"}]
Each Java Object contains arrays in Platform and language key like this example:
{"name"="Demo","platform"=[{"id"="1","value"="ios"},{"id"="2","value"="android"}],"language"=[{"id"="1","value"="eng"}],"date"="20/05/2018"}
This is the output expected in text/plain type:
{"name":"Demo","platform":[{"id":"1","value":"ios"},{"id":"2","value":"android"}],"language":[{"id":"1","value":"eng"}],"date":"20/05/2018"}
{"name":"Kernel","platform":[{"id":"1","value":"macos"},{"id":"2","value":"linux"}],"language":[{"id":"1","value":"ger"}],"date":"20/05/2018"}
Each object from Java to JSON
Indent=false per line
No brackets or commas between objects. Each object per line
Must not affect Platform and Language key arrays
Is it possible to apply this without having to play with String replace?
So you can use the write function to transform each element to application/json and with the writer property indent=false
%dw 2.0
output text/plain
---
payload map ((item, index) -> write(item, "application/json", {indent: false})) reduce ((item, accumulator) -> item ++ "\n" ++ accumulator)
Or if you use mule 4.2 you can directly use application/x-ndjson and it should work directly
%dw 2.0
output application/x-ndjson
---
payload

How to remove Double Quote in JSON Array

I searched through this forum but did not get similar case of removing double quotes in JSON array.
This is my part request format
"customer_address_list":[{"email_address" :{"email_to" : ""},
"method" : "EMAIL",
"customer_id" : ""}]
As this is dynamic values I putting values with push of JSON in for loop. Something like this in my js
Request_Format.customer_address_list.push( XXXXXXXXXXX) ;
Every time there is unwanted double quotes appending in every entry like
"customer_address_list":[
"{"email_address":"email_to":"xyz.pqqr#companyname.com"},"method":"EMAIL","customer_id":"1"}",
"{"email_address":"email_to":"zzz.aaaa#companyname.com"},"method":"EMAIL","customer_id":"2"}",
"{email_address":"email_to":"www.aaaa#companyame.com"},"method":"EMAIL","customer_id":"3"}"]
Due to this additional double quote at start and end of every entry, Final JSON became invalid.
All above code shared is in java script
Is there any work around to remove this double quotes
Thanks in advance
If you are using Python, you can convert each string to a dictionary literal using the eval function
customer_as_dict = eval(customer_as_string)
To remove the quotes around the name customer_address_list, you may be able to use
eval("customer_address_list") = [eval(customer_as_string) for customer_as_string in dict_as_string]

Different outputs when printing Python bytearray of list

I am trying to convert a list of integers to bytearray in Python 2.7
input code:
bytearray([1,2,120,120])
output:
bytearray(b'\x01\x02xx')
But when I try to "print" the same bytearray, I am getting some wired characters.
input code:
print bytearray([1,2,120,120])
output:
??xx
Are they both same? What is the reason behind this?
If you want to get bytearray(b'\x01\x02xx') you need to use the __repr__ method of a bytearray object:
print repr(bytearray([1,2,120,120]))
By default __str__ in invoked, that returns a string representation of a byte array. And that string contains the \x01\x02 that are not printable characters, hence you see question marks.
References:
https://docs.python.org/2/library/functions.html#repr

Resources