【发布时间】:2019-10-03 03:40:53
【问题描述】:
我有这个 JSON 对象:
{
"type": "FeatureCollection",
"features": [
{
"id": "0eb3d8a7d9afa466766e90b47f2bd785",
"type": "Feature",
"properties": {
"feature-description": "<div id=\"content\">html content here</div>"
},
"geometry": {
"coordinates": [
[
[
144.87452272951856,
-37.72702750630904
],
[
145.00292543948336,
-37.78131678501029
],
[
145.12926821291518,
-37.732458226660285
],
[
145.11278872073137,
-37.70801684893612
],
[
144.9184680420177,
-37.72431199679091
],
[
144.87452272951856,
-37.72702750630904
]
]
],
"type": "Polygon"
}
}
]
}
如果我JSON.stringify 它并尝试在 PHP 中解码:
$jsonString = '"{\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"id\": \"0eb3d8a7d9afa466766e90b47f2bd785\",\n \"type\": \"Feature\",\n \"properties\": {\n \"feature-description\": \"<div id=\"content\">html content here</div>\"\n },\n \"geometry\": {\n \"coordinates\": [\n [\n [\n 144.87452272951856,\n -37.72702750630904\n ],\n [\n 145.00292543948336,\n -37.78131678501029\n ],\n [\n 145.12926821291518,\n -37.732458226660285\n ],\n [\n 145.11278872073137,\n -37.70801684893612\n ],\n [\n 144.9184680420177,\n -37.72431199679091\n ],\n [\n 144.87452272951856,\n -37.72702750630904\n ]\n ]\n ],\n \"type\": \"Polygon\"\n }\n }\n ]\n}"';
$json = json_decode( $jsonString );
echo gettype($json); // string
我仍然得到string,而不是object。我做错了什么?
【问题讨论】:
-
为了将来参考,您可以使用 json_last_error() 返回最后发生的错误。 php.net/manual/en/function.json-last-error.php
-
“JSON.stringify() 方法将 JavaScript 对象或值转换为 JSON 字符串...”developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 换句话说,它创建了 JSON。你不会在已经存在的 JSON 上运行它,否则你最终会得到你所拥有的。