Brian
Brian

Reputation: 4418

How do I convert a string with single quotes into double for json parse

I have an array that is being encoded in php using json_encode

 $params = array(1=>'something','2'=>'two');

When I encode it using json encode it will encode it with double quotes which in itself is fine but I'm trying to embed this in an anchor tag and the double quotes are messing up the attributes. <a class="btn ajax" data-method="test" data-params="{"one":"something","2":"two"}" href="#">test ajax link</a>

obviously the second double quote in the data-params attribute is breaking the link.

So what I did was convert the string into single quotes but I need to re-convert it to double quotes to be able to parse in javascript;

 var string = {'one':'something','2':'two'} ;

JSON.parse will fail on that string, i tried

 var jsonString = dataParams.replace('\'', '"');

but that seems to only convert the first single quote then stops. Any ideas?

Upvotes: 4

Views: 10091

Answers (2)

Matt
Matt

Reputation: 75327

A better approach would be to use the htmlentities() function to encode the " as &quot;, meaning you can insert it as data-*. When you retrieve it using JavaScript, they'll show up as ", meaning you can JSON.parse it immediately;

<a data-foo="<?php echo htmlentities(json_encode(array('demo' => 'test'))); ?>">Hey</a>
<script>alert(JSON.parse(document.getElementsByTagName("a")[0].dataset.foo).demo);</script>

Upvotes: 3

antyrat
antyrat

Reputation: 27765

Use this instead:

var jsonString = dataParams.replace(/'/g, '"');

Upvotes: 0

Related Questions