[英]json_encode and JSON.parse does not harmonize
I get this output on my php page with json_encode 我在我的php页面上使用json_encode获得此输出
{"id":"761","user":"Moderator","message":"test"}
{"id":"760","user":"Patrick","message":"test"}
Now i want to parse theses values with JSON.parse in javascript, to get an array. 现在我想用javascript中的JSON.parse解析这些值,以获得一个数组。 But it does not work.
但这行不通。
It works only if i have one json Objekt. 它只有在我有一个json Objekt时才有效。
What is the best way to solve this? 解决此问题的最佳方法是什么?
To split at '}' and parse every string that i will get? 要在“}”处拆分并解析我将得到的每个字符串?
{}{}
is not valid JSON. {}{}
是无效的JSON。 You need to have an array wrap these and separate them with commas like [{},{}]
. 您需要一个数组将它们包装起来,并用
[{},{}]
类的逗号分隔。 You can do this in PHP via: 您可以通过以下方式在PHP中执行此操作:
$entries = array();
foreach ($database_entry as $array) {
$entries[] = $array;
}
echo json_encode($entries);
That is you should only call json_encode
once . 那就是你应该只调用一次
json_encode
。
This output is not a proper JSON object or array. 此输出不是正确的JSON对象或数组。 What you want to do is wrap your objects in square brackets, and separate them with commas.
您要做的是将对象包装在方括号中,并用逗号分隔。 The output should look like this:
输出应如下所示:
[{"id":"761","user":"Moderator","message":"test"},
{"id":"760","user":"Patrick","message":"test"}]
You will need to change your PHP to generate the output in this way. 您将需要更改PHP以这种方式生成输出。
You'll need to output the objects into a JSON array, with each object/array item separated by a comma: 您需要将对象输出到JSON数组中,每个对象/数组项均以逗号分隔:
{
"users": [
{"id":"761","user":"Moderator","message":"test"},
{"id":"760","user":"Patrick","message":"test"}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.