note:
{"category_id":"1","name":"Notes","icon":"images\/note.png"},
quote:
{"category_id":"2","name":"Quotes","icon":"images\/quote.png"},
project:
{"category_id":"3","name":"Projects","icon":"images\/project.png"},
skill:
{"category_id":"4","name":"Skills","icon":"images\/skill.png"}
这是我的控制台中显示的内容。我已将json_decode
用于我的查询,并与字符串连接,我相信这是问题的原因。
那么如何将字符串数据转换为json格式呢?
答案 0 :(得分:5)
如果那是字符串,那么我建议将其包装在{
... }
中并使用`JSON.parse。即:
var json = JSON.parse('{' + string + '}');
当然,您需要将JSON lib帮助器添加到页面https://github.com/douglascrockford/JSON-js
答案 1 :(得分:0)
你可以使用JSON.parse(string)
这将从你的字符串中返回一个JSON
答案 2 :(得分:0)
我认为你的PHP有问题而不是Javascript:
你已经解码了一个JSON字符串,用于在json_decode
处理它的PHP对象中对其进行转换...但现在你必须以格式良好的JSON字符串取回它。
但首先你的字符串无效,对于JSON标准(在PHP中):
必须将{strong>注释,引用,项目,技能的名称封装在"
内
,你的新字符串:
{ “注意”:{ “CATEGORY_ID”: “1”, “名称”: “注释”, “图标”: “图像/ note.png”}, “引用”:{ “CATEGORY_ID”: “2”, “名称”: “报价”, “图标”: “图像/ quote.png”}, “项目”{ “CATEGORY_ID”: “3”, “名”: “项目”, “图标”: “图像/ project.png”}, “技能”:{ “CATEGORY_ID”: “4”, “名称”: “技能”, “图标”: “图像/ skill.png”} }
现在在PHP中看到这个JSON编码的例子:
$yourString = '{"note":{"category_id":"1","name":"Notes","icon":"images\/note.png"},"quote":{"category_id":"2","name":"Quotes","icon":"images\/quote.png"},"project":{"category_id":"3","name":"Projects","icon":"images\/project.png"},"skill":{"category_id":"4","name":"Skills","icon":"images\/skill.png"}}';
$JSON_FOR_PHP = json_decode($yourString);
$JSON_FOR_JS = json_encode($JSON_FOR_PHP);
/* response: */
echo "JSON for PHP (associative Array):<br><br>";
var_dump($JSON_FOR_PHP);
echo"<br><br>";
echo "JSON for JAVASCRIPT (JSON string {add content type: application/json}):<br><br>";
echo $JSON_FOR_JS;
响应:
JSON for PHP (associative Array):
object(stdClass)#1 (4) { ["note"]=> object(stdClass)#2 (3) { ["category_id"]=> string(1) "1" ["name"]=> string(5) "Notes" ["icon"]=> string(15) "images/note.png" } ["quote"]=> object(stdClass)#3 (3) { ["category_id"]=> string(1) "2" ["name"]=> string(6) "Quotes" ["icon"]=> string(16) "images/quote.png" } ["project"]=> object(stdClass)#4 (3) { ["category_id"]=> string(1) "3" ["name"]=> string(8) "Projects" ["icon"]=> string(18) "images/project.png" } ["skill"]=> object(stdClass)#5 (3) { ["category_id"]=> string(1) "4" ["name"]=> string(6) "Skills" ["icon"]=> string(16) "images/skill.png" } }
JSON for JAVASCRIPT (JSON string {add content type: text/json}):
{"note":{"category_id":"1","name":"Notes","icon":"images\/note.png"},"quote":{"category_id":"2","name":"Quotes","icon":"images\/quote.png"},"project":{"category_id":"3","name":"Projects","icon":"images\/project.png"},"skill":{"category_id":"4","name":"Skills","icon":"images\/skill.png"}}
如果您只回显$JSON_FOR_JS
并将内容类型更改为 application / json ,则会得到响应是一个有效的JSON字符串,您可以在javascript中使用JSON.parse()
进行解析:< / p>
header('Content-Type: application/json');
echo $JSON_FOR_JS;
或直接在JS脚本(html页面或.js文件中没有脚本标记)中回显:
var js_json = JSON.parse();现在在javascript中你有一个带有字符串内容的对象js_json。