Google scripts - Gosu - variable syntax - gosu

Whats the syntax required in order to insert a variable to a json string in Gosu script. I have this var:
var mydate = '"' + todayString + '"';
Currently I am truing to insert this var inside a JSON string as the following but I get an error:
{
"brandId": "10820",
"dateRange": "CUSTOM",
"startDate": "2016-08-15",
**"endDate": "+mydate+"**
}
I know that in Javascript it should be like that:
"endDate": '${mydate}'
Whats the required syntax for Gosu? thank you.

A String literal example:
uses java.time.LocalDate
uses gw.lang.reflect.json.Json
var mydate = LocalDate.now();
var json = '{ \
"brandId": "10820", \
"dateRange": "CUSTOM", \
"startDate": "2016-08-15", \
"endDate": "${mydate}" \
}'
var bindings: Dynamic = Json.fromJson(json)
print(bindings.endDate)
Read https://gosu-lang.github.io/2016/03/01/new-json-support-in-gosu.html for more information regarding JSON support in Gosu.

Related

Trying to add array element to a maybe existing config file

I'm testing the following:
#!/usr/bin/env bash
element="$(jo -p \
locations=["$(jo \
name="$name" \
address="$address" \
latitude=$lat \
longitude=$long \
gridId=$grid_id \
gridX=$grid_X \
gridY=$grid_Y \
countyUGC="$countyUGC" \
zoneUGC="$zoneUGC" \
stationId="$stationId")"])"
if [[ -e weather.locations ]]; then
jq --argjson element "$element" '. += $element' \
weather.locations >weather.locations.temp && mv weather.locations.temp weather.locations
else
echo "$entry" >weather.locations
fi
The 1st time I run this, the file will not exist (reason for my [[ ]]). But subsequent times, it seems to always modify the initial element instead of adding. My goal: Append location array with new element (I don't see any need for updating, but "name" would be the field to key off of)
output of the jo: (of course all the fields would be filled in)
{
"locations": [
{
"name": "home",
"address": "123 Main St, MyTown MyState",
"latitude": null,
"longitude": null,
"gridId": null,
"gridX": null,
"gridY": null,
"countyUGC": null,
"zoneUGC": null,
"stationId": null
}
]
}
Thanks for any pointers
Your jo command produces an object with a "locations" field, whose value will be used to replace the one of the existing object (. refers to the outlying object rather than to its "locations" array).
Instead you'll want the following :
jq --argjson element "$element" '.locations += $element.locations'

JQ - how to convert CSV with headers to JSON array with nested dictionaries

I got the following CSV sample
key1,key2,key3,key4,key5
val1,val2,val3,val4,val5
Looking for tips how to convert the above structure into the following JSON structure
[
{
"event": "bleep",
"sourcetype": "rats",
"fields": {
"key1":"val1",
"key2":"val2",
"key3":"val3",
"key4":"val4",
"key5":"val5"
}
},
{
"event": "bleep",
"sourcetype": "rats",
"fields": {
"key1":"val1",
"key2":"val2",
"key3":"val3",
"key4":"val4",
"key5":"val5"
}
}
]
Thanks in advance!
Use -R to read the input as raw text
jq -R '
(. / ",") as $keys
| [ inputs / "," | [$keys, .]
| reduce transpose[] as $i (
{event: "bleep", sourcetype: "rats"}; .fields[$i[0]] = $i[1])
]
' input.csv
Demo
Alasql lib can load the data file from server, parse it and put the result to array of JSON objects.
So, this is some example for you:
<script src="alasql.min.js"></script>
<script>
alasql('SELECT * FROM CSV("FileName.csv",{headers:true})',[],function(res){
var dataResult = {items:res};
});
</script>

Parsing JSON dict of CloudFormation parameters for '--parameter-overrides'

I'm using AWS CloudFormation at the moment, and I need to parse out parameters due to differences between stack creation and deployment. Command aws cloudformation create accepts a JSON file, but aws cloudformation deploy only accepts inlined application parameters of Key=Value type.
I have this JSON file:
[
{
"ParameterKey": "EC2KeyPair",
"ParameterValue": "$YOUR_EC2_KEY_PAIR"
},
{
"ParameterKey": "SSHLocation",
"ParameterValue": "$YOUR_SSH_LOCATION"
},
{
"ParameterKey": "DjangoEnvVarDebug",
"ParameterValue": "$YOUR_DJANGO_ENV_VAR_DEBUG"
},
{
"ParameterKey": "DjangoEnvVarSecretKey",
"ParameterValue": "$YOUR_DJANGO_ENV_VAR_SECRET_KEY"
},
{
"ParameterKey": "DjangoEnvVarDBName",
"ParameterValue": "$YOUR_DJANGO_ENV_VAR_DB_NAME"
},
{
"ParameterKey": "DjangoEnvVarDBUser",
"ParameterValue": "$YOUR_DJANGO_ENV_VAR_DB_USER"
},
{
"ParameterKey": "DjangoEnvVarDBPassword",
"ParameterValue": "$YOUR_DJANGO_ENV_VAR_DB_PASSWORD"
},
{
"ParameterKey": "DjangoEnvVarDBHost",
"ParameterValue": "$YOUR_DJANGO_ENV_VAR_DB_HOST"
}
]
And I want to turn it into this:
'EC2KeyPair=$YOUR_EC2_KEY_PAIR SSHLocation=$YOUR_SSH_LOCATION DjangoEnvVarDebug=$YOUR_DJANGO_ENV_VAR_DEBU
G DjangoEnvVarSecretKey=$YOUR_DJANGO_ENV_VAR_SECRET_KEY DjangoEnvVarDBName=$YOUR_DJANGO_ENV_VAR_DB_NAME D
jangoEnvVarDBUser=$YOUR_DJANGO_ENV_VAR_DB_USER DjangoEnvVarDBPassword=$YOUR_DJANGO_ENV_VAR_DB_PASSWORD Dj
angoEnvVarDBHost=$YOUR_DJANGO_ENV_VAR_DB_HOST'
This would be the equivalent Python code:
thing = json.load(open('stack-params.example.json', 'r'))
convert = lambda item: f'{item["ParameterKey"]}={item["ParameterValue"]}'
>>> print(list(map(convert, thing)))
['EC2KeyPair=$YOUR_EC2_KEY_PAIR', 'SSHLocation=$YOUR_SSH_LOCATION', 'DjangoEnvVarDebug=$YOUR_DJANGO_ENV_V
AR_DEBUG', 'DjangoEnvVarSecretKey=$YOUR_DJANGO_ENV_VAR_SECRET_KEY', 'DjangoEnvVarDBName=$YOUR_DJANGO_ENV_
VAR_DB_NAME', 'DjangoEnvVarDBUser=$YOUR_DJANGO_ENV_VAR_DB_USER', 'DjangoEnvVarDBPassword=$YOUR_DJANGO_EN$
_VAR_DB_PASSWORD', 'DjangoEnvVarDBHost=$YOUR_DJANGO_ENV_VAR_DB_HOST']
>>> ' '.join(map(convert, thing))
'EC2KeyPair=$YOUR_EC2_KEY_PAIR SSHLocation=$YOUR_SSH_LOCATION DjangoEnvVarDebug=$YOUR_DJANGO_ENV_VAR_DEBU
G DjangoEnvVarSecretKey=$YOUR_DJANGO_ENV_VAR_SECRET_KEY DjangoEnvVarDBName=$YOUR_DJANGO_ENV_VAR_DB_NAME D
jangoEnvVarDBUser=$YOUR_DJANGO_ENV_VAR_DB_USER DjangoEnvVarDBPassword=$YOUR_DJANGO_ENV_VAR_DB_PASSWORD Dj
angoEnvVarDBHost=$YOUR_DJANGO_ENV_VAR_DB_HOST'
I have this little snippet:
$ cat stack-params.example.json | jq '.[] | "\(.ParameterKey)=\(.ParameterValue)"'
"EC2KeyPair=$YOUR_EC2_KEY_PAIR"
"SSHLocation=$YOUR_SSH_LOCATION"
"DjangoEnvVarDebug=$YOUR_DJANGO_ENV_VAR_DEBUG"
"DjangoEnvVarSecretKey=$YOUR_DJANGO_ENV_VAR_SECRET_KEY"
"DjangoEnvVarDBName=$YOUR_DJANGO_ENV_VAR_DB_NAME"
"DjangoEnvVarDBUser=$YOUR_DJANGO_ENV_VAR_DB_USER"
"DjangoEnvVarDBPassword=$YOUR_DJANGO_ENV_VAR_DB_PASSWORD"
"DjangoEnvVarDBHost=$YOUR_DJANGO_ENV_VAR_DB_HOST"
But I'm not sure how to join the strings together. I was looking at reduce but I think it only works on lists, and streams of strings aren't lists. So I'm thinking the correct approach is to convert the key : value association into 'key=value' strings within the list, then join altogether, though I have trouble working with the regex. Does anybody have any tips?
The goal as exemplified by the illustrative output seems highly dubious, but it can easily be achieved using the -r command-line option together with the filter:
map("\(.ParameterKey)=\(.ParameterValue)") | "'" + join(" ") + "'"
Footnote
I was looking at reduce but I think it only works on lists, and streams of strings aren't lists.
To use reduce on a list, say $l, you could simply use [] as in:
reduce $l[] as $x (_;_)

jq syntax help for querying lists output

I need help in correcting jq test cases syntax. Following is output file & trying to test ID list with command below. Gives error index to string type.
[[ $(echo $output| jq -r '.output.value[] | select(.identity).id_list') == *"id2"* ]]
output = {
"resource_output": {
"value": {
"identity": [
{
"id_list": [
"/subscriptions/---/id1",
"/subscriptions/---/id2",
"/subscriptions/--/id3"
],
"principal_id": "",
"tenant_id": "",
"type": "managed"
}
]
}
}
Your query does not match the sample JSON, and you have not indicated what output you are expecting, but the following variation of your query illustrates how to use select and test with your data along the lines suggested by your attempt:
echo "$output" |
jq -r '.resource_output.identity[].id_list[] | select(test("id2"))'
Output:
/subscriptions/---/id2

DynamoDB: How to append values into the List (Array) of an existing Item

(I'm using AWS PHP SDK)
Let's say i have a Table:
Table name: article
Primary partition key: article_id (Number)
With a sample of manually created Item:
{
"article_id": 10010,
"updated": "2018-02-22T20:15:19.28800Z",
"comments": [ "Nice article!", "Thank you!" ]
}
Adding new comment:
I know how to entirely update (overwrite) this existing Item, in this way:
$key = $marshaler->marshalJson('
{
"article_id": 10010
}
');
$eav = $marshaler->marshalJson('
{
":u": "2018-02-22T20:15:19.28800Z",
":c": [ "Nice article!", "Thank you!", "This is the new one!" ]
}
');
$params = [
'TableName' => 'article',
'Key' => $key,
'ExpressionAttributeValues'=> $eav,
'UpdateExpression' => 'set updated=:u, comments=:c',
'ReturnValues' => 'UPDATED_NEW'
];
I can somehow APPEND new values (aka) add new comment, this way. But this is literally still recreating the whole entire Item again, which is not the way i preferred.
How do i just simply APPEND new values into an List/Array inside an existing Item, please?
Add elements to the list
When you use SET to update a list element, the contents of that element are replaced with the new data that you specify. If the element does not already exist, SET will append the new element at the end of the list.
Create Table
aws dynamodb create-table \
--table-name article \
--attribute-definitions AttributeName=article_id,AttributeType=N \
--key-schema AttributeName=article_id,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1
Add item
aws dynamodb put-item \
--table-name article \
--item '{
"article_id": {"N": "123"},
"updated": {"S": "00:00:00"},
"comments": {
"L": [
{ "S": "Nice article!" },
{ "S": "Thank you!" }
]}
}'
Update Item
aws dynamodb update-item \
--table-name article \
--key '{"article_id":{"N":"123"}}' \
--update-expression "SET comments[50] = :c, updated=:u" \
--expression-attribute-values '{
":u": {"S": "01:01:01"},
":c": {"S": "This is the new one!"}
}' \
--return-values ALL_NEW
List comments[] contain two elements (index 0 and 1) before the update. As comments[50] doesn't exist, the SET operation will append it to the end of the list (comments[2]).

Resources