0

I want to convert "['2022-03-24', '2022-03-25']" to javascript array data is from element.dataset

did const dateRange = JSON.stringify("['2022-03-24', '2022-03-25']") JSON.parse(dateRange) returns ['2022-03-24', '2022-03-25'] which is a string and not a javaScript array.

I want to populate date range with flatpickr with object from my database so I'm passing the date html element via data attribute <input type="date" class="date-range" data-date="{{date_range}}" />

  • 1
    make the original string is valid JSON (use double quotes) and then just parse it. `JSON.parse('["2022-03-24", "2022-03-25"]')` – pilchard Mar 16 '22 at 21:36
  • No; using parse directly on it throws this error VM24785:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 1 at JSON.parse () at (index):531:30 at NodeList.forEach () at flatpickrDate ((index):530:19) at (index):541:5 – Cynthia Onyilimba Mar 16 '22 at 21:43
  • 2
    As i said, make sure it's valid first (double quotes, not single around array elements). Also see: [Encoding JSON with strings in html data attributes](https://stackoverflow.com/questions/34215369/encoding-json-with-strings-in-html-data-attributes) – pilchard Mar 16 '22 at 21:44
  • 1
    also: [Using JSON in django template](https://stackoverflow.com/questions/6286192/using-json-in-django-template) – pilchard Mar 16 '22 at 21:50

2 Answers2

0

Try that, it would leave you with array of date strings, try to parse them to dates now (if you need).

someString.replace(/[',\]\[]/g, '').split(' ')
Kohan14
  • 34
  • 3
0

You can use the Function() object to create an instance of a function that will return an array. The second line below creates an anonymous function which is then immediately invoked via ().

const arrString = "['2022-03-24', '2022-03-25']";
const arr = (new Function(`return ${arrString}`))();
console.log( arr );

DEMO

const arrString = "['2022-03-24', '2022-03-25']";
const arr = (new Function(`return ${arrString}`))();
console.log( arr );
PeterKA
  • 24,158
  • 5
  • 26
  • 48