admin管理员组文章数量:1390641
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 02 Answers
Reset to default 3A better approach would be to use the htmlentities()
function to encode the "
as "
, 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, '"');
本文标签: javascriptHow do I convert a string with single quotes into double for json parseStack Overflow
版权声明:本文标题:javascript - How do I convert a string with single quotes into double for json parse - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744575376a2613591.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论