为了账号安全,请及时绑定邮箱和手机立即绑定

如何从javascript中的JSON响应中删除双引号?

如何从javascript中的JSON响应中删除双引号?

PHP
繁星点点滴滴 2021-04-29 10:11:49
我正在尝试将多个标记添加到Google地图中,并且在这里找到了一种方法。现在,我从服务器收到一个json数组响应,如下所示。 // function to get user names and addressespublic function getUserAddresses(Request $request){    $users = User::where('address', '!=', null)->select('name', 'address')->get();  //this is a laravel query    $userData = [];    foreach ($users as $user) {        $userData[$user->name] = $user->address;    }    return $userData;}上面的代码是给我以下响应的原因。{  "plumber1": "-1.2523238641713191,36.87899683074249",  "plumber2": "-1.2192245641713191,36.87899687428849",  "allan plumber": "-1.2192238641713191,36.87899683068849"}但对于我来说,要使用此数据,它必须采用以下javascript中所示的格式。[   ["plumber1", -1.2523238641713191,36.87899683074249],   ["plumber2", -1.2192245641713191,36.87899687428849],   ["allan plumber", -1.2192238641713191,36.87899683068849]];
查看完整描述

2 回答

?
德玛西亚99

TA贡献1770条经验 获得超3个赞

您可以使用此php代码


$str = '{

  "plumber1": "-1.2523238641713191,36.87899683074249",

  "plumber2": "-1.2192245641713191,36.87899687428849",

  "allan plumber": "-1.2192238641713191,36.87899683068849"

}';


$array =json_decode($str);

$new_array = [];

foreach ($array as $key => $value) {

  $coordinates = explode(',',$value);

  $coordinate1 = (float) $coordinates[0];

  $coordinate2 = (float) $coordinates[1];

  $new_array[] = array($key,$coordinate1,$coordinate2);

}

print_r($new_array);

输出


        Array

(

    [0] => Array

        (

            [0] => plumber1

            [1] => -1.25232386

            [2] => 36.878996830742

        )


    [1] => Array

        (

            [0] => plumber2

            [1] => -1.2192245641713

            [2] => 36.878996874288

        )


    [2] => Array

        (

            [0] => allan plumber

            [1] => -1.2192238641713

            [2] => 36.878996830688

        )


)

您也可以在此处查看演示,


这是Javascript版本


    <script type="text/javascript">

var str = `{

  "plumber1": "-1.2523238641713191,36.87899683074249",

  "plumber2": "-1.2192245641713191,36.87899687428849",

  "allan plumber": "-1.2192238641713191,36.87899683068849"

}`;

var obj = JSON.parse(str);

var array = [];

var counter =0;

for (var key in obj) {

  var myarr =  obj[key].split(",");

    array[counter] = [key, parseFloat(myarr[0]), parseFloat(myarr[1])];

    counter++

}

console.log(array);

</script>


查看完整回答
反对 回复 2021-05-07
?
千巷猫影

TA贡献1829条经验 获得超7个赞

尝试 json_decode


ini_set( 'precision', 17 );


$jsonToArray = json_decode($json, JSON_NUMERIC_CHECK);


查看完整回答
反对 回复 2021-05-07
  • 2 回答
  • 0 关注
  • 220 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信