最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I convert a string with single quotes into double for json parse - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Jul 20, 2012 at 12:56 BrianBrian 4,41814 gold badges63 silver badges105 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 3

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>

Use this instead:

var jsonString = dataParams.replace(/'/g, '"');
发布评论

评论列表(0)

  1. 暂无评论