0

I created a Google Application Script that from a sheet generates data for Tabulator.js. As a string. When I copy the text and place it into my html file it works but I load it via Google Appliacation Script call and such string I assign to Tabulator data variable I get an error Data Loading Error - Unable to process data due to invalid data type Expecting: array , Received: string

Is there any simple way to convert such string to needed array of JSON structure? Note the children for the first row. You can play with it in jsFiddle

I tried to use JSON.parse but it looks like the string structure is not good SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data"

[
  {id:1, name:"BalanceOil", _children:
    [
      {id:2, name:"BalanceOil+  s testy", cena:31},
      {id:3, name:"BalanceOil+ ", cena:31}
    ]
  },
  {id:11, name:"Xtend x2 Kit", cena:23},
  {id:18, name:"Viva+ Kit", cena:21}
]

The original data look like below but I simplified it.

[{id:1, name:"BalanceOil", _children:
    [{id:2, name:"BalanceOil+  s testy", cena:31, mn:1,cena_1:"", package:159, kredityMesicne:4, kredityBalik:14},
     {id:3, name:"BalanceOil+ ", cena:31, mn:1,cena_1:"", package:85, kredityMesicne:4, kredityBalik:8},]},
 {id:11, name:"Xtend x2 Kit", cena:23, mn:1,cena_1:"", package:83, kredityMesicne:3, kredityBalik:8},
 {id:18, name:"Viva+ Kit", cena:21, mn:1,cena_1:"", package:60, kredityMesicne:3, kredityBalik:4}
]

Is it possible to use the source of data as a string or I have to change the code a create the structure as the desired object? What would it actually be? an array or JSON?

Radek
  • 13,813
  • 52
  • 161
  • 255

1 Answers1

1

Multiple ways to achieve this

  1. eval although it could be VERY VERY dangerous if the content passed inside it is not 100% trustworthy as this is simply dynamic code injection/evaluation.

// from your jsfiddle
var asTextOriginal ='[{id:1, name:"BalanceOil", _children:[{id:2, name:"BalanceOil+  s testy", cena:31, mn:1,cena_1:"", package:159, kredityMesicne:4, kredityBalik:14},{id:3, name:"BalanceOil+ ", cena:31, mn:1,cena_1:"", package:85, kredityMesicne:4, kredityBalik:8},]},{id:11, name:"Xtend x2 Kit", cena:23, mn:1,cena_1:"", package:83, kredityMesicne:3, kredityBalik:8},{id:18, name:"Viva+ Kit", cena:21, mn:1,cena_1:"", package:60, kredityMesicne:3, kredityBalik:4}]';
eval(asTextOriginal);
  1. manually parse whole string and create array/object out of it: String to object in JS

  2. configure the script to return an actual JSON instead string

PS: the snippet won't run here again because of security reason, though you can try putting it in console

Harsh Gundecha
  • 1,139
  • 9
  • 16
  • 1
    Eval() works smoothly. Thank you. I will probably change the script that generates data though. – Radek Jan 19 '21 at 11:03