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

时间:2019-04-20 14:27:13

标签: javascript php arrays json

我正在尝试在Google地图中添加多个标记,并且找到了一种方法here。 现在,我从服务器收到一个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]
];

2 个答案:

答案 0 :(得分:0)

尝试json_decode

ini_set( 'precision', 17 );

$jsonToArray = json_decode($json, JSON_NUMERIC_CHECK);

答案 1 :(得分:0)

您可以使用此php代码

john: 2
marry: 4

输出

$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);

您还可以查看演示here

这是Javascript版本

        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
        )

)