×

Please give details of the problem

Skip to content

How to convert an Array to a JSONObejct 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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<#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-->

<#assign my_array = {"col1":["a","b"],"col2":["c","d"],"col3":["e","f"]}>

${my_array}  
<#assign my_array1 = transpose(my_array)>  
${my_array1}  
${transpose_1(my_array1)}  
${transpose_1(my_array1,["col1","col2"])} <#-- to retrieve only columns col1 and col2 ( not col3)

<#-- will return -->

{"col1":["a","b"],"col2":["c","d"],"col3":["e","f"]} <#-- json of arrays -->
[{"col1":"a","col2":"c","col3":"e"},{"col1":"b","col2":"d","col3":"f"}] <#-- array of jsons -->
{"col1":["a","b"],"col2":["c","d"],"col3":["e","f"]}
{"col1":["a","b"],"col2":["c","d"]}