elaspog
elaspog

Reputation: 1709

Array of maps in PineScript

Is it possible to define list of maps in Pinescript and use it as a function of a library?

I want to do something like this in the library code:

// @function Converts map of strings to a flat JSON string.
// @param data The map of key value pairs.
// @returns JSON string for simple map.
export dict_to_json(simple map<string, string> data) =>
    simple string [] arr = array.new_string()
    for [key, val] in data
        array.push(arr, "\"" + key + "\":\"" + val + "\"")
    "{" + array.join(arr, ",") + "}"

// @function Converts array of maps to an JSON array string.
// @param data The array of map of key value pair strings.
// @returns JSON array string for array of simple maps.
export array_of_maps_to_json(??? array<map<string, string>> data) =>
    simple string [] arr = array.new_string()
    for [i, data_point] in data
        array.push(arr, dict_to_json(data_point))
    "[" + array.join(arr, ",") + "]"

For this I can't figure out how the signature of the array_of_maps_to_json(...) function should look like.
Does anyone have any idea?


Meanwhile I've found a disgusting solution. I really hope that's not the only workaround.

dict_to_json(simple map<string, string> data) =>
    simple string [] arr = array.new_string()
    for [key, val] in data
        array.push(arr, "\"" + key + "\":\"" + val + "\"")
    "{" + array.join(arr, ",") + "}"

type mydict
    map<string, string> dict

array_of_maps_to_json(mydict[] data) =>
    simple string [] arr = array.new_string()
    for [i, data_point] in data
        array.push(arr, dict_to_json(data_point.dict))
    "[" + array.join(arr, ",") + "]"

simple mydict [] arr = array.new<mydict>()
array.push(arr, mydict.new(data1))
array.push(arr, mydict.new(data2))
json_data := array_of_maps_to_json(arr)

Upvotes: 0

Views: 520

Answers (1)

Starr Lucky
Starr Lucky

Reputation: 1961

You can create array of maps by using types. Create type that has map as its field. Then you can create array of types and iterate trough them

export type myMap
    map<string, string> jsonmap = na

export array_of_maps_to_json(myMap[] data) =>
   ...

Upvotes: 2

Related Questions