PHP json_encode()结果显示JSONLint错误

时间:2012-09-21 00:21:13

标签: php json jsonlint

我在验证json_encode()功能的输出方面遇到了问题。

我使用cURL提取XML Feed,将其转换为数组,然后使用json_endode()将该数组转换为JSON。我会饶恕你的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自然

Wikipedia有详细记录的页面

W3Resource对结构有一个很好的解释。

JSONLint

1 个答案:

答案 0 :(得分:1)

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

正确的语法是

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

你需要注意的事情是

  • [ ] wrap
  • 用逗号分隔对象

<强>解决方案

$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);