2

我在验证json_encode()函数的输出时遇到问题。

我正在使用 cURL 提取 XML 提要,将其转换为数组,然后将该数组转换为带有json_endode(). 我会为你省去 cURL 的东西:

  foreach ($xmlObjects->articleResult as $articleResult) {
    $article = array(
      "articleResult" =>
      array(
        'articleId' => (string)$articleResult->articleId,
        'title' => (string)$articleResult->title,
        'subhead' => (string)$articleResult->subhead,
        'tweet' => (string)$articleResult->tweet,
        'publishedDate' => (string)$articleResult->publishedDate,
        'image' => (string)$articleResult->image
      ),
    );
    $json = str_replace('\/','/',json_encode($article));
    echo $json;
  }

这给了我一个 JSON 读数:

{
    "articleResult": {
        "articleId": "0001",
        "title": "Some title",
        "subhead": "Some engaging subhead",
        "tweet": "Check out this tweet",
        "publishedDate": "January 1st, 1970",
        "image": "http://www.domain.com/some_image.jpg"
    }
}
{
    "articleResult": {
        "articleId": "0002",
        "title": "Some title",
        "subhead": "Some engaging subhead",
        "tweet": "Check out this tweet",
        "publishedDate": "January 1st, 1970",
        "image": "http://www.domain.com/some_image.jpg"
    }
}

这会给我一个 JSONLint 错误说:

Parse error on line 10:
..._120x80.jpg"    }}{    "articleResult
---------------------^
Expecting 'EOF', '}', ',', ']'

所以很自然地我会添加逗号,这给了我一个文件结束的期望:

Parse error on line 10:
..._120x80.jpg"    }},{    "articleResu
---------------------^
Expecting 'EOF'

我是 JSON 新手,但我已经检查了网站和一些资源以了解正确的 JSON 格式和结构,从我可以看到我的读数遵循指南。任何指针?

我检查过的资源:

JSON.org自然

维基百科有据可查的页面

W3Resource对结构有很好的解释。

JSONLint

4

1 回答 1

2

您将 2+ 个对象编码为 json 字符串,您需要[ ]将它们包装起来

正确的语法是

[ 
   { /* first object */ }
 , { /* second object */ }
 , { /* third object */ }
]

你需要注意的是

  • [ ]
  • 用逗号分隔对象

解决方案

$json = array();
foreach ($xmlObjects->articleResult as $articleResult) {
  $article = array(
    "articleResult" =>
    array(
      'articleId' => (string)$articleResult->articleId,
      'title' => (string)$articleResult->title,
      'subhead' => (string)$articleResult->subhead,
      'tweet' => (string)$articleResult->tweet,
      'publishedDate' => (string)$articleResult->publishedDate,
      'image' => (string)$articleResult->image
    ),
  );
  $json[] = $article;
}
echo json_encode($json);
于 2012-09-21T00:27:09.383 回答