将字符串数据转换为json格式

这个问题在这里已经有了答案:

  • 安全地将JSON字符串转换为对象22个答案

  • 如果这是字符串,那么我会建议把它包装在{ ... }并使用`JSON.parse。 即:

    var json = JSON.parse('{' + string + '}');
    

    当然,你将需要添加JSON lib助手到你的页面https://github.com/douglascrockford/JSON-js


    你可以使用JSON.parse(string)这将返回一个JSON字符串


    我认为你有一个问题与PHP不使用JavaScript:

    你已经解码了一个JSON字符串,用于在PHP对象中使用json_decode处理它,但是现在你必须以良好格式的JSON字符串取回它。

    但首先你的字符串是无效的,对于JSON标准(在PHP中):

  • 把你的字符串放在{
  • 属性注释,报价,项目,技能名称必须封装在里面" ,你的新字符串:

    {“note”:{“category_id”:“1”,“name”:“Notes”,“icon”:“images / note.png”},“quote”:{“category_id”:“2”,“name “:”引用“,”icon“:”images / quote.png“},”project“{”category_id“:”3“,”name“:”Projects“,”icon“:”images / project.png“ },“skill”:{“category_id”:“4”,“name”:“技能”,“icon”:“images / skill.png”}}

  • 现在在PHP中看到这个JSON encodingi的例子:

    $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()进行解析:

    header('Content-Type: application/json');
    echo $JSON_FOR_JS;
    

    或直接在JS脚本(html页面或在.js文件中没有脚本标签)中回显它:

    var js_json = JSON.parse();

    现在在JavaScript中,你有一个包含你的字符串内容的js_json对象。

    链接地址: http://www.djcxy.com/p/31711.html

    上一篇: turn string data into json format

    下一篇: Why does instanceof return false for some literals?