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

我正在尝试将多个标记添加到Google地图中,并且在这里找到了一种方法。现在,我从服务器收到一个json数组响应,如下所示。


 // function to get user names and addresses

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

];


繁星点点滴滴
浏览 221回答 2
2回答

德玛西亚99

您可以使用此php代码$str = '{&nbsp; "plumber1": "-1.2523238641713191,36.87899683074249",&nbsp; "plumber2": "-1.2192245641713191,36.87899687428849",&nbsp; "allan plumber": "-1.2192238641713191,36.87899683068849"}';$array =json_decode($str);$new_array = [];foreach ($array as $key => $value) {&nbsp; $coordinates = explode(',',$value);&nbsp; $coordinate1 = (float) $coordinates[0];&nbsp; $coordinate2 = (float) $coordinates[1];&nbsp; $new_array[] = array($key,$coordinate1,$coordinate2);}print_r($new_array);输出&nbsp; &nbsp; &nbsp; &nbsp; Array(&nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => plumber1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => -1.25232386&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [2] => 36.878996830742&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [1] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => plumber2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => -1.2192245641713&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [2] => 36.878996874288&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [2] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => allan plumber&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => -1.2192238641713&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [2] => 36.878996830688&nbsp; &nbsp; &nbsp; &nbsp; ))您也可以在此处查看演示,这是Javascript版本&nbsp; &nbsp; <script type="text/javascript">var str = `{&nbsp; "plumber1": "-1.2523238641713191,36.87899683074249",&nbsp; "plumber2": "-1.2192245641713191,36.87899687428849",&nbsp; "allan plumber": "-1.2192238641713191,36.87899683068849"}`;var obj = JSON.parse(str);var array = [];var counter =0;for (var key in obj) {&nbsp; var myarr =&nbsp; obj[key].split(",");&nbsp; &nbsp; array[counter] = [key, parseFloat(myarr[0]), parseFloat(myarr[1])];&nbsp; &nbsp; counter++}console.log(array);</script>

千巷猫影

尝试 json_decodeini_set( 'precision', 17 );$jsonToArray = json_decode($json, JSON_NUMERIC_CHECK);
打开App,查看更多内容
随时随地看视频慕课网APP