简体   繁体   English

如何将带单引号的字符串转换为double用于json解析

[英]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 我有一个使用json_encode在php中编码的数组

 $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. 当我使用json编码对其进行编码时,它将使用双引号对其进行编码,这本身就很好但我正在尝试将其嵌入到锚标记中并且双引号会弄乱属性。 <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. 很明显,data-params属性中的第二个双引号是破坏链接。

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; 所以我做的是将字符串转换为单引号,但我需要将其重新转换为双引号,以便能够在javascript中解析;

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

JSON.parse will fail on that string, i tried JSON.parse会在该字符串上失败,我试过了

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

but that seems to only convert the first single quote then stops. 但这似乎只转换第一个单引号然后停止。 Any ideas? 有任何想法吗?

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; 更好的方法是使用htmlentities()函数" as &quot;进行编码,这意味着您可以将其作为data-*插入。当您使用JavaScript检索它时​​,它们将显示为" ,意味着您可以使用JSON.parse立即JSON.parse ;

<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>

请改用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM