How to convert an Array to a JSON Obejct and vice versa
To dump a RMP array (json of arrays) to a google spreadsheet, you have to create an array of jsons: you'll have to use ${transpose(my_array)}.
To dump the rows of a google spreadsheet (array of jsons) to a RMP array (json of arrays), you have to use ${transpose_1(my_array)} defined below.
Code:
<#function transpose_1 my_array my_keys=[]>
${my_array?size}
<#if my_array?is_sequence>
<#if (my_array?size > 0)>
<#if (my_keys?size != 0)>
<#assign array_keys = my_keys>
<#else>
<#assign array_keys = []>
<#list my_array[0]?keys as x>
<#assign array_keys = array_keys + [x]>
</#list>
</#if>
</#if>
<#assign my_result = {}>
<#list array_keys as x>
<#assign my_col = []>
<#list my_array as y>
<#assign my_col = my_col + [y[x]?default("")]>
</#list>
<#assign my_json = "{\"" + x + "\":" + my_col + "}">
<#assign my_json = my_json?eval>
<#assign my_result = (my_result + my_json)?eval>
</#list>
<#else>
<#assign my_result = "error while executing function tranpose_1">
</#if>
<#return my_result>
</#function>
Result:
<#assign my_array = {"col1": ["a","b"], "col2": ["c","d"], "col3": ["e","f"]}>
${my_array}
<!-- json of arrays
{
"col1": ["a","b"],
"col2":["c","d"],
"col3":["e","f"]
}
-->
<#assign my_array1 = transpose(my_array)>
${my_array1}
<!-- array of jsons
[
{
"col1": "a",
"col2": "c",
"col3": "e"
},
{
"col1": "b",
"col2": "d",
"col3": "f"
}
]
-->
${transpose_1(my_array1)}
<!--
{
"col1": ["a", "b"],
"col2": ["c", "d"],
"col3": ["e", "f"]
}
-->
<!-- to retrieve only columns col1 and col2 (not col3)-->
${transpose_1(my_array1,["col1", "col2"])}
<!--
{
"col1": ["a", "b"],
"col2": [ "c", "d"]
}
-->
Please give details of the problem