【问题标题】:Json Encoding FormatJson 编码格式
【发布时间】:2014-07-22 09:13:55
【问题描述】:

我正在尝试制作一个远程连接到数据库并运行查询的 iPhone 应用程序。我有一个运行查询并将结果数组编码为 json 的 php 脚本。我一直在关注本教程 (http://codewithchris.com/iphone-app-connect-to-mysql-database/) 并且目前有相同的 php 文件代码。但是,当我回显 json 数组时,我得到的输出格式不同。

我正在关注的教程具有以下格式的输出;

[
   - {
        Name: "Apple",
        Address: "1 Infinite Loop Cupertino, CAL"
      }, 
...

但是,我看到这样的事情:

[{"Name":"Apple", "Address":"1 Infinite Loop Cupertino, CAL"}], ....

我很困惑,它们是否相同(我有关联键)?有人可以解释什么可能导致输出差异(相同的代码)以及如何将格式更改为所需的格式吗?稍后当我在 Xcode 日志中打印出 json 数组时,我会看到不一致的情况,例如:

"Name" = Apple;
Address = "Infinite Loop Cupertino, CAL";
... 

(我什至得到格式“x”=“x”;)

这是 php 文件中的代码:

$con->set_charset("utf8");
$resultArray = array();

// Check if there are results
if ($result = mysqli_query($con, $sql)) {
    // Loop through each row in the result set
    while($row = $result->fetch_object()){
        $resultArray[] = $row;
    }
}

echo json_encode($resultArray);

【问题讨论】:

  • 你得到的是有效的 JSON。您展示的第一个示例是 not 有效的 JSON。我假设它是一个调试器视图或一个示例,但它肯定不是 JSON。两者似乎都显示相同的数据结构,所以一切似乎都很好。
  • 所以我的问题可能在于我如何在 Xcode 中下载 Json 文件...谢谢您为我解决这个问题

标签: php mysql arrays json


【解决方案1】:

您确实得到了有效的 JSON,json_encode 默认打印最小版本,不包括空格和换行符等。

您可能看到的是带有 JSON_PRETTY_PRINT 标志的 json_encode

json_encode($data, JSON_PRETTY_PRINT);

(我没有检查这个所以我不能确定,我的 PHP 版本是旧的)

请参阅:http://php.net/manual/en/function.json-encode.php 了解更多信息

【讨论】:

  • 感谢您的解释。我将专注于如何在 Xcode 上下载我的 Json 来解决我的问题。
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多