PHP - 从JSON响应中删除\n

hey*_*red 1 php json newline

我有一个API调用的(简化的)JSON响应,如下所示

{"status":true,"action_values":"{\n \"range_from\": \"0\",\n \"range_to\": \"0\"\n}"}
Run Code Online (Sandbox Code Playgroud)

我试图使用PHP从上面删除\n字符,但它似乎没有工作.

我尝试:

$trimmed = str_replace("\n", "", $response);
Run Code Online (Sandbox Code Playgroud)

其中$ response是我的JSON字符串,如上所述.但是这不会删除/替换\n字符.

jer*_*oen 7

无需删除\n/换行.

相反,您应该使用解码您的字符串json_decode(),然后您可以解码该range_from值,该值也是在原始json中编码的json:

<?php
$str = '{"status":true,"action_values":"{\n \"range_from\": \"0\",\n \"range_to\": \"0\"\n}"}';

$dec = json_decode($str, true);

var_dump(json_decode($dec['action_values'], true));
Run Code Online (Sandbox Code Playgroud)

结果:

array(2) {
  ["range_from"]=>
  string(1) "0"
  ["range_to"]=>
  string(1) "0"
}
Run Code Online (Sandbox Code Playgroud)

一个例子.