How to create a JSON array as string from groovy objects? - arrays

I have some data in Groovy's objects which I need to convert to a JSON string array. The final result should be..
[
{
"keys":{
"passcode": "12345"
},
"values":{
"EmailAddress": "john#doe.com",
"message": "Hello, is it me you are looking for?"
}
}
]
I found this post but the accepted answer which uses JSON Builder didn't make sense and the second answer using JSON converter didn't work...
def deJson = [
keys: [
passcode: secretCode
],
values: [
EmailAddress:emailData.to[0],
message: content.message
]
] as grails.converters.JSON
This created a JSON object when I needed an array.
Can anyone suggest how I can use JSON Builder or JSON converter to create an array string like I have above?

JSON is specific to Grails (as mentioned in one of the comments in the answer from the previous post). You should have followed the question itself in the post, that has the answer.
Using groovy.json.JsonBuilder, the expected way to serialize would be:
def jsonObj = [
keys: [
passcode: secretCode
],
values: [
EmailAddress:emailData.to[0],
message: content.message
]
]
// In order to get a json array, use a list containing the object
new JsonBuilder([jsonObj]).toPrettyString()

Related

Using jq to parse nested JSON arrays

I have a bash script that defines a function that returns dynamic JSON as a result:
# inside bash script
numInstances=getInstances();
Where an example of the JSON returned by getInstances() is:
[
[
{
"id": 193932,
"name": "foobaz"
},
{
"id": 28348,
"name": "fizzbuzz"
}
]
]
It's important to note that although the JSON is dynamic, it will always be a nested JSON array of the form:
[
[
<json list here; this is what I need a count of>
]
]
How can I pipe jq to the output of getInstances() so that it will parse the JSON and return the number of instances inside the nested JSON array? For example, in the above output, there are 2 "instances" inside the nested JSON array. So I would want numInstances to be set to 2, etc.
.[0]|length
would suffice, but is not very robust against a violation of assumptions.

Iterating a JSON array in LogicApps

I'm using a LogicApp triggered by an HTTP call. The call posts a JSON message which is a single row array. I simply want to extract the single JSON object out of the array so that I can parse it but have spent several hours googling and trying various options to no avail. Here's an example of the array:
[{
"id": "866ef906-5bd8-44d8-af34-0c6906d2dfd7",
"subject": "Engagement-866ef906-5bd8-44d8-af34-0c6906d2dfd7",
"data": {
"$meta": {
"traceparent": "00-dccfde4923181d4196f870385d99cb84-52b8333f100b844c-00"
},
"timestamp": "2021-10-19T17:01:06.334Z",
"correlationId": "866ef906-5bd8-44d8-af34-0c6906d2dfd7",
"fileName": "show.xlsx"
},
"eventType": "File.Uploaded",
"eventTime": "2021-10-19T17:01:07.111Z",
"metadataVersion": "1",
"dataVersion": "1"
}]
Examples of what hasn't worked:
Parse JSON on the array, error: InvalidTemplate when specifiying an array as the schema
For each directly against the http output, error: No dependent actions succeeded.
Any suggestions would be gratefully received.
You have to paste the example that you have provided to 'Use sample payload to generate schema' in the Parse JSON Connector and then you will be able to retrieve each individual object from the sample payload.
You can extract a single JSON object from your array by using its index in square brackets. E.g., in the example below you'd need to use triggerBody()?[0] instead of triggerBody(). 0 is an index of the first element in the array, 1 - of the second, and so on.
Result:

Logic Apps - looping through a nested array in JSON

I need to loop through this optional array (it's only the sectional of JSON I have trouble with).
As you can see from the code:
The optional bullseye has an array rings. rings has arrays of expansionCriteria and expansionCriteria may or may not have actions.
How do I iterate and get all type, threshold in expansionCriteria? I also need to access all skillsToRemove under actions, if available.
I am rather new to Logic Apps, so any help is appreciated.
"bullseye": {
"rings": [
{
"expansionCriteria": [
{
"type": "TIMEOUT_SECONDS",
"threshold": 180
}
],
"actions": {
"skillsToRemove": [
{
"name": "Claims Foundation",
"id": "60bd469a-ebab-4958-9ca9-3559636dd67d",
"selfUri": "/api/v2/routing/skills/60bd469a-ebab-4958-9ca9-3559636dd67d"
},
{
"name": "Claims Advanced",
"id": "bdc0d667-8389-4d1d-96e2-341e383476fc",
"selfUri": "/api/v2/routing/skills/bdc0d667-8389-4d1d-96e2-341e383476fc"
},
{
"name": "Claims Intermediate",
"id": "c790eac3-d894-4c00-b2d5-90cd8a69436c",
"selfUri": "/api/v2/routing/skills/c790eac3-d894-4c00-b2d5-90cd8a69436c"
}
]
}
},
{
"expansionCriteria": [
{
"type": "TIMEOUT_SECONDS",
"threshold": 5
}
]
}
]
}
Please let me know if you need more info.
To generate the schema, you can remove the name of the object at the top of the code: "bullseye":
Thank you pramodvalavala-msft for posting your answer in MS Q&A for the similar thread .
" As you are working with a JSON Object instead of an Array, unfortunately there is no built-in function to loop over the keys. There is a feature request to add a method to extract keys from an object for scenarios like this, that you could up vote for it gain more traction.
You can use the inline code action to extract the keys from your object as an array (using Object.keys()). And then you can loop over this array using the foreach loop to extract the object that you need from the main object, which you could then use to create records in dynamics."
For more information you can refer the below links:
. How to loop and extract items from Nested Json Array in Logic Apps .
.Nested ForEach Loop in Workflow. .

Use Node.js to parse JSON array that does not contain JSON objects

How can I parse this object using node.js? I am trying to extract 3.25. Thanks
"data": [["2020-05-04", 3.25],....]
Never mind. I got it.
data[0][1]
I think this is much more suitable way to fetch data from your payload.
let val = {
"data": [ [ "2020-05-04", 3.25 ], [ "2020-05-14", 1.25 ], [ "2020-02-04", 2.25 ]]
};
//-------------------------------
val["data"].forEach((element)=>{
console.log(element[1]);
});
//-----------Or------------------
val["data"][0][1];

FCM Field "data" must be a JSON array

Hi im working with postman to make my json object FCM message:
But when i try to send:
{
"to":"fzvihT7dFUI:APA91bFVhnWAxXVjlWiiHIs9ZUyL1DE2hZO6GpItJtReh3hcKF1kD6mLuQq9fNP9xvS5bOFWUOG-OW-uyOedc1C43m8jfvD4OOfsBYuMbM7t1-dZEy2kQcuv3gJw6dhneVus2AR_hQHQ",
"data":[
{
"time":1501385514224,
"CC":"1030626890"
}
],
"notification":{
"body":"SPO2:95 \nPulso:75",
"title":"El paciente Daniel Ortiz nesecita asistencia"
}
}
The response its:
Field "data" must be a JSON array:
[{"CC":"1030626890","time":1501385514224}]
But i know the [{"CC":"1030626890","time":1501385514224}] its a array, i dont understand the problem.
What i made wrong?
From the Firebase Cloud Messaging documentation, it seems like data should be a JSON object:
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data" : {
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
},
}
I'm not sure why the error message talks says it needs to be an array. It's like meant as an "associative array" which is really just another term for a JSON object.
I might be too late but for those who still face this problem , following change saved me.
By adding JSON_FORCE_OBJECT to json_encode() it will add missing braces so it should be something like this:
json_encode($fields ,JSON_FORCE_OBJECT));
That's it.
In case you serialize sql/api results data that each item of the array has a numeric key using php, for example an array like:
$results = [
['name'=>'john', 'durname'=>'doe'],
['chuck'=>'john', 'durname'=>'Norris'],
]
Before turning into FCM data try:
$results = [
["time":1501385514224, "CC":"1030626890"]
["time":1501385514334, "CC":"1030126890"]
]
$fcmData = [
"to"=>"fzvihT7dFUI:APA91bFVhnWAxXVjlWiiHIs9ZUyL1DE2hZO6GpItJtReh3hcKF1kD6mLuQq9fNP9xvS5bOFWUOG-OW-uyOedc1C43m8jfvD4OOfsBYuMbM7t1-dZEy2kQcuv3gJw6dhneVus2AR_hQHQ",
"data":[
"data" => $results
],
"notification" => [
"body"=>"SPO2:95 \nPulso:75",
"title"=>"El paciente Daniel Ortiz nesecita asistencia"
]
]
$fcmData = json_encode($fcmData);
// Send push notification here
In case you are using laravel with brozot/laravel-fcm, a good approach is this one.
Thje bottom line is that fcm/push notification data MUST be an associative array.

Resources