【问题标题】:How to Convert string response to array laravel如何将字符串响应转换为数组 laravel
【发布时间】:2021-12-05 19:10:11
【问题描述】:

我想将此响应更改为数组
这是我通过 API 收到的值:"{'db_password': 'TgD31F#4124!'}"
我想删除引号,只保留TgD31F#4124!

代码示例

$db = Http::get(HERE_URL);
return $db->body(); // received it here "{'db_password': 'TgD31F#4124!'}"

【问题讨论】:

标签: php json laravel


【解决方案1】:

您应该在响应变量上使用json() 方法或object() 方法。 API Reference

json method: Get the JSON decoded body of the response as an array or scalar value.
object method: Get the JSON decoded body of the response as an array or scalar value.

用法:

$response = Http::get("www.api.com/...");
$decodedBody = $response->json();

$decodedBody = $response->object();

编辑: 所有可用的方法都列在the documentation中。

【讨论】:

  • 对不起,还是同样的错误
  • 您是否尝试使用$decodedBody['db_password'] 来访问您想要的字段值?看起来你做错了什么,因为这是有效的文档。
【解决方案2】:

在 ajax 中添加数据类型:json 然后 response.db_password

否则,尝试将其解析为 json。 let RESULT = JSON.parse(response) console.log(RESULT.db_password)

【讨论】:

  • 我不能通过 php 在 ajax 中做到这一点,因为它是 api 响应
  • 您可以尝试两种可能的解决方案:$result = $db->body()->toArray();$result = json_encode($db->body()); return $result->db_password;
猜你喜欢
  • 1970-01-01
  • 2021-09-02
  • 2019-09-13
  • 2020-06-20
  • 2022-11-19
  • 2020-12-19
  • 2021-12-13
  • 2021-09-24
  • 1970-01-01
相关资源
最近更新 更多