[英]Correctly Format JSON Output in PHP
I am retrieving the name of an employee from one API and need to format some JSON to transmit it over an outgoing api.我正在从一个 API 中检索员工的姓名,需要格式化一些 JSON 以通过传出的 api 传输它。 I need my output to look like this.我需要我的 output 看起来像这样。
A {"employees":[{"name":"Charles Johnson"}]}
Right now my output looks like this:现在我的 output 看起来像这样:
B {"employees":"[{\"name\":\"Robert Johnson\"}]"}
based on the following code:基于以下代码:
$employee = "Robert Johnson";//string retrieved from API
$return = json_encode(array(array('name'=>$employee)));
echo json_encode(array('employees'=>$return));
How can I convert B so it looks like A. Note I would prefer not to alter the last line (echo...) as it is used for various other things as well.如何转换 B 使其看起来像 A。注意我不希望更改最后一行(echo ...),因为它也用于各种其他事情。 'd like to prep $return so that it echoes out in the form of A. '想要准备 $return 以便它以 A 的形式回显。
Thanks for any suggestions.感谢您的任何建议。
Json encode is required only once after preparing all the data. Json 编码在准备好所有数据后只需要一次。 Please find the below code hope it will help you.请找到以下代码,希望对您有所帮助。
$employee = "Robert Johnson";//string retrieved from API
$return =array(array('name'=>$employee));
echo json_encode(array('employees'=>$return));
You encode JSON data twice so just do it once, in last line that outputs it.您对 JSON 数据进行两次编码,因此只需执行一次,在最后一行输出它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.