我在验证json_encode()函数的输出时遇到了问题。
我使用cURL引入一个XML,将其转换为数组,并使用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
发布于 2012-09-21 08:27:09
您正在将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);https://stackoverflow.com/questions/12522738
复制相似问题