Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert a string representation of array back to array?

I am trying something out...

Say I have this:

<div id="helloworld" 
     call="chart" 
     width="350" height="200" 
     value="[[4, 8, 1, 88, 21],[45, 2, 67, 11, 9],[33, 4, 63, 4, 1]]" 
     label="['test1', 'test2', 'test3', 'test4', 'test5']"/>

I am using jQuery to fetch my all the element attribute into an object array, that part worked, and I am getting something like this:

Object { id="helloworld", call="chart" ... }

The second part I need to do is to convert the "String representation of the array" into an actual array, it works for my value using JASON.parse() for the value... however trying to do the same thing with the label didn't work, it doesn't like the single quote (') I have in there... Tried escaped it with \" still no dice.

Does anyone know an elegant way to convert it back into an array?

like image 317
codenamezero Avatar asked Aug 25 '26 02:08

codenamezero


2 Answers

As you're using jQuery, and custom attributes, the first thing to fix is the attributes:

Instead of:

<div id="helloworld" 
     call="chart" 
     width="350" height="200" 
     value="[[4, 8, 1, 88, 21],[45, 2, 67, 11, 9],[33, 4, 63, 4, 1]]" 
     label="['test1', 'test2', 'test3', 'test4', 'test5']" />

You should use:

<div id="helloworld" 
     data-call="chart" 
     width="350" height="200" 
     data-value="[[4, 8, 1, 88, 21],[45, 2, 67, 11, 9],[33, 4, 63, 4, 1]]" 
     data-label='["test1", "test2", "test3", "test4", "test5"]'></div>

Be sure to also use valid JSON encoding for your data.

When you do that, you can access the values of the attributes with jQuery's .data() method

$('#helloworld').data('label'); //returns the actual array

In some cases you may want to use .attr() to access the string representation of the attribute.


If you absolutely must leave the data as it was, and you can guarantee that the "strings" won't contain special characters, you could call $.parseJSON($('#helloworld').attr('data-label').replace("'", '"'));, but it will fail if the string contains quotes or other special characters that are not correctly encoded/escaped.

like image 57
zzzzBov Avatar answered Aug 26 '26 17:08

zzzzBov


Since your string looks like it's JSON you use JSON.parse. JSON doesn't allow ' so you can't parse the label.

Is there any chance you can change how that HTML is generated? If you generate it with proper HTML encoding you can easily parse it to JSON.

<div label="[&quot;test1&quot;, &quot;test2&quot;, &quot;test3&quot;, &quot;test4&quot;, &quot;test5&quot;]">

JSON.parse(elm.label); // should work
like image 34
Halcyon Avatar answered Aug 26 '26 17:08

Halcyon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!