How to Convert a string to lua code to read value from nested table - lua-table

I have a configurable value of a table fetch function which i get as an input string. I need that string to be executed as a code and fetch a value from the nested table.
I tried using load(string), its not working
local function main()
local t = {
["name1"] = "value1",
["name2"] = {["name1"] = "value1",
["name2"] = { 1, false, true, 23.54, "a \021 string" },
name3 = nil
},
name3 = nil
}
local string = 't.name2.name1'
print(type(string))
print(load(string))
end
print(load(string)) should print value1.

Below code works
local function main()
t = {
["name1"] = "value1",
["name2"] = {["name1"] = "value1",
["name2"] = { 1, false, true, 23.54, "a \021 string" },
name3 = nil
},
name3 = nil
}
string = "t.name2.name1"
print(type(string))
val = load("return "..string)()
print(val)
end

Related

Return multiple results with index terraform

I currently have the below lists,
local.security_list =
[
{
ocid = security_list_id_1
name = subnet1
},
{
ocid = security_list_id_2
name = subnet1
},
{
ocid = security_list_id_3
name = subnet2
},
{
name = subnet2
ocid = security_list_id_4
},
]
var.vcn_security_lists = [
{
security_list_name = security_list_1
subnet_name = subnet1
},
{
security_list_name = security_list_2
subnet_name = subnet1
},
{
security_list_name = security_list_3
subnet_name = subnet2
}
]
I want to create the security lists using the var.vcn_security_lists list and then assign them to the subnet later on by using the subnet_name field. I have done this previously using the index() function as below, which loops through a subnet and pulls out the security list with the same subnet name. The problem is that this only returns one item - how can I return multiple from a list ?
subnet_security_list_ocid = [local.security_list[index(local.security_list.*.name,var.vcn_security_lists[index(var.vcn_security_lists.*.subnet_name,var.vcn_subnets[count.index].subnet_name)].security_list_name)].id]

Iterate through a yaml file that key name changes

I have tried a couple of ways to iterate through a map in yaml but each results i keep getting errors ex: local.settings is object with # attributes .
to start with here is my yaml and locals setup
config:
params:
server:
host: 127.0.0.1
port: 8080
media:
name: foobar
type: html
s3:
bucket: foobarbucket
uploadFolder: folderfoobar
type:
public: false
email:
to: noreply#foobar.com
locals {
settings = yamldecode(file("test.yaml"))
}
module "store_write" {
source = "cloudposse/ssm-parameter-store/aws"
for_each = local.settings.variables
parameter_write = [
{
name = "/settings/${each.key}(i need each param key name ex: server)/${each.key.NEXTKET}(then the following key name after ex:host)"
value = "${each.key.value}(that keys value, ex: 127.0.0.1)"
type = "String"
overwrite = "true"
description = "Terraform deployed param: ${local.app_name} ${each.key}"
}
]
}
now of course i get an output of whats decoded from the yaml file, but every for loop i try wont work. at this point i cant even find 1 that is clean enough to paste here. i dont think i can achieve what i need IF sometimes the key names ex: s3 or email change over time right?
also notice sometimes i might get 3 levels,
config:
params:
s3:
bucket: foobarbucket
uploadFolder: folderfoobar
type:
public: false
I got a bit further in trying the following and had to edit the yaml file a bit. BUT now im getting duplicates
locals {
params = yamldecode(file("./test.yaml"))["app"]
folder_project_apis = flatten([
for fk, param in local.params : [
for pk, config in param.params : [
for lk, name in config : [
for vk, value in config : {
key1 = fk
key2 = pk
key3 = lk
value = value
}
]
]
]
])
}
using new yaml structure
app:
testing: #fk
display_name: "Folder A"
parent:
params:
server: #pk
host:
- 127.0.0.1
port:
- 3000
s3:
layout:
- "uploads"
image:
- "total"
outputs
> local.folder_project_apis
[
{
"key1" = "testing"
"key2" = "s3"
"key3" = "image"
"value" = [
"total",
]
},
{
"key1" = "testing"
"key2" = "s3"
"key3" = "image"
"value" = [
"uploads",
]
},
{
"key1" = "testing"
"key2" = "s3"
"key3" = "layout"
"value" = [
"total",
]
},
{
"key1" = "testing"
"key2" = "s3"
"key3" = "layout"
"value" = [
"uploads",
]
},
{
"key1" = "testing"
"key2" = "server"
"key3" = "host"
"value" = [
"127.0.0.1",
]
},
{
"key1" = "testing"
"key2" = "server"
"key3" = "host"
"value" = [
3000,
]
},
{
"key1" = "testing"
"key2" = "server"
"key3" = "port"
"value" = [
"127.0.0.1",
]
},
{
"key1" = "testing"
"key2" = "server"
"key3" = "port"
"value" = [
3000,
]
},
]
If i understand correctly, you want to iterate through a map in the file 'test.yaml' and access objects ? You can do below.
outputs.tf
output host{
value = local.settings.params.server.host
}
output email {
value = local.settings.params.email
}
terraform output
email = {
"to" = "noreply#foobar.com"
}
host = "127.0.0.1"
And you have concern that if key value is changed then you cannot access above parsing of yaml objects , yes, that is correct.
For example, if I change 's3' to 's4' in the given file and terraform apply.
entire key-value of s3 is removed and inserted of s4
~ params = {
- s3 = {
- bucket = "foobarbucket"
- uploadFolder = "folderfoobar"
} -> null
+ s4 = {
+ bucket = "foobarbucket"
+ uploadFolder = "folderfoobar"
}
# (3 unchanged elements hidden)
}
}

How to map column to complex object in SlickGrid

var data = [{"Id":40072,"Id2":40071,"SmDetails":{"Id1":40071,"Id2":40072}}]
I want to display SmDetails.Id1 in a column. How is this possible? I tried:
var columns = [{name:'Personnel',field:SmDetails.id1,id:'detailId'}];
Please help me
Please help me
**My latest code**
var data = [{"Id":40072,"Id2":40071,"allocationDetails":{"Id1":40071,"allocationDetails":{"accommodationId":4007}}}]
var grid;
var columns = [ {name:"Personnel",field:"allocationDetails",fieldIdx:'accommodationId', id:"accommodationId"}];
var options = {
enableCellNavigation: true,
enableColumnReorder: false,
dataItemColumnValueExtractor:
function getValue(item, column) {
var values = item[column.field];
if (column.fieldIdx !== undefined) {
return values && values[column.fieldIdx];
} else {
return values;
}}};
var gridData=$scope.Vo;//This return as json format
grid = new Slick.Grid("#testGrid",gridData, columns);
This is the code tried recently.
You'll need to provide a custom value extractor to tell the grid how to read your object.
var options = {
enableCellNavigation: true,
enableColumnReorder: false,
dataItemColumnValueExtractor:
// Get the item column value using a custom 'fieldIdx' column param
function getValue(item, column) {
var values = item[column.field];
if (column.fieldIdx !== undefined) {
return values && values[column.fieldIdx];
} else {
return values;
}
}
};
The column definitions would look like:
{
id: "field1",
name: "Id1",
field: "SmDetails",
fieldIdx: 'Id1'
}, {
id: "field2",
name: "Id2",
field: "SmDetails",
fieldIdx: 'Id2'
} //... etc
Check out this fiddle for a working example.
try this to convert your data into object of single length values ...
newData = {};
for(key in data[0]){
parentKey = key;
if(typeof(data[0][key]) == "object"){
childData = data[0][key];
for(key in childData){
childKey = key;
newKey = parentKey+childKey;
newData[newKey] = childData[childKey];
}
} else {
newData[key] = data[0][key];
}
}
This will convert your data object like this
newData = {Id: 40072, Id2: 40071, SmDetailsId1: 40071, SmDetailsId2: 40072};
Now use this newData to map your data items in grid
I find this works well for nested properties, eg:
var columns = [
{ id: "someId", name: "Col Name", field: "myRowData.myObj.myProp", width: 40}
..
];
var options {
...
dataItemColumnValueExtractor: function getItemColumnValue(item, column) {
var val = undefined;
try {
val = eval("item." + column.field);
} catch(e) {
// ignore
}
return val;
}
};

How do I format this json correctly?

Having a problem translating my json code form this dataObject...
var dataObject = {
"timeline":
{
"headline":"The Main Timeline Headline Goes here",
"type":"default",
"text":"<p>Intro body text goes here, some HTML is ok</p>",
"asset": {
"media":"http://yourdomain_or_socialmedialink_goes_here.jpg",
"credit":"Credit Name Goes Here",
"caption":"Caption text goes here"
},
"date": [
{
"startDate":"2011,12,10",
"endDate":"2011,12,11",
"headline":"Headline Goes Here",
"text":"<p>Body text goes here, some HTML is OK</p>",
"asset": {
"media":"http://twitter.com/ArjunaSoriano/status/164181156147900416",
"thumbnail":"optional-32x32px.jpg",
"credit":"Credit Name Goes Here",
"caption":"Caption text goes here"
}
}
],
"era": [
{
"startDate":"2011,12,10",
"endDate":"2011,12,11",
"headline":"Headline Goes Here",
"text":"<p>Body text goes here, some HTML is OK</p>",
}
]
}
}
into this method...
def timeline
t = {}
t['timeline'] = {}
t['timeline']['headline'] = "Lorem"
t['timeline']['text'] = "default"
t['timeline']['asset'] = {}
t['timeline']['asset']['media'] = ""
t['timeline']['asset']['credit'] = ""
t['timeline']['asset']['caption'] = ""
t['timeline']['date'] = [{}]
t['timeline']['date']['startDate'] = "2011,12,10"
t['timeline']['date']['endDate'] = "2011,12,11"
t['timeline']['date']['headline'] = ""
t['timeline']['date']['text'] = ""
t['timeline']['date']['asset'] = {}
t['timeline']['date']['asset']['media'] = ""
t['timeline']['date']['asset']['thumbnail'] = ""
t['timeline']['date']['asset']['credit'] = ""
t['timeline']['date']['asset']['caption'] = ""
t['timeline']['era'] = [{}]
t['timeline']['era']['startDate'] = "2011,12,10"
t['timeline']['era']['endDate'] = "2011,12,11"
t['timeline']['era']['headline'] = ""
t['timeline']['era']['text'] = ""
return t
end
specifically I'm uncertain about
t['timeline']['date'] = [{}]
and
t['timeline']['era'] = [{}]
How should I properly write those lines?
t['timeline']['date'] = [{}]
that should work just fine. Only you have to add attributes slightly different. Like this:
t['timeline']['date'][0]['startDate'] = "2011,12,10"
^^^
first element in the array
Just build a hash directly:
def timeline
{
"timeline" = {
"headline" = "Lorem",
"text" = "default",
"asset" = {}
},
"date" = [{
"startDate" = "2011,12,10",
"asset" = {
"media" = ""
}
}]
}
end
Saves a lot of typing, and will mentally map much more naturally to JSON.

How to project simple data set into to anonymous type of a different shape

I have a simple set of data that I am having trouble figuring out how to create the projection I want using LINQ.
public class Score {
public string Name { get; set; }
public int Value { get; set; }
}
var scores = new List<Score> {
new Score { Name = "jesse", Value = 10 },
new Score { Name = "jesse", Value = 12 },
new Score { Name = "jesse", Value = 15 },
new Score { Name = "billy", Value = 5 },
new Score { Name = "billy", Value = 7 },
new Score { Name = "billy", Value = 20 },
new Score { Name = "colin", Value = 25 },
new Score { Name = "colin", Value = 13 },
new Score { Name = "colin", Value = 8 }
};
I need to project 'scores' into an anonymous type with the following structure.
{
series : [
{ name : "jesse", data : [10, 12, 15 ] },
{ name : "billy", data : [ 5, 7, 20 ] },
{ name : "colin", data : [25, 13, 8 ] }
]
}
Any help is appreciated.
var result = new {
series = from score in scores
group score.Value by score.Name into nameValues
select new
{
name = nameValues.Key,
data = nameValues
}
};
Does this match the structure you want?
var query = scores.GroupBy(s => s.Name);
var result = query.Select(q => new {
Name = q.Key,
Data = q.ToArray().Select(k => k.Value)
});
var anotherAnon = new {series = result.ToArray()};

Resources