turn string data into json format
1 2 3 4 5 6 7 8 | 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格式呢?
如果这是绳子,那么我建议用
1 | var json = JSON.parse('{' + string + '}'); |
当然,您需要将json lib helper添加到您的页面https://github.com/douglascorkford/json-js中。
我认为你对php有问题,而不是对javascript有问题:
您已经用
但首先,对于JSON标准(在PHP中),您的字符串无效:
属性的名称note、quote、project、skill必须封装在
{"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"}
现在看看下面这个用PHP编写的JSON编码示例:
1 2 3 4 5 6 7 8 9 10 | $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):"; var_dump($JSON_FOR_PHP); echo""; echo"JSON for JAVASCRIPT (JSON string {add content type: application/json}):"; echo $JSON_FOR_JS; |
回应:
1 2 3 4 5 6 7 | 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"}} |
如果只回送
1 2 | header('Content-Type: application/json'); echo $JSON_FOR_JS; |
或者直接将其回送到JS脚本中(HTML页或.JS文件中不带脚本标记):
var js_json=json.parse();现在在JavaScript中,您有一个对象JS_json,其中包含字符串的内容。
您可以使用