【问题标题】:What is the simplest method of programmatically adding data to JSON?以编程方式将数据添加到 JSON 的最简单方法是什么?
【发布时间】:2013-07-11 07:25:14
【问题描述】:

对于 PHP/HTML 页面,向 JSON 添加数据的最简单方法是什么? 我应该使用 PHP、JS 还是 jQuery?

我尝试了网上找到的许多不同的方法,但我无法使用任何方法。我已经尝试了所有这些,但我无法完全正确。

 var myObject = new Object();
 JSON.stringify()
 JSON.parse()
 $.extend();
 .push()
 .concat()

我已经加载了这个 JSON 文件

    {"commentobjects": 
        [
                {"thecomment": "abc"},
                {"thecomment": "def"},
                {"thecomment": "ghi"}
            ]
    }

我想以编程方式添加

    var THISNEWCOMMENT = 'jkl;
    {"thecomment": THISNEWCOMMENT}

这样 JSON 变量将是

    {"commentobjects": 
        [
                {"thecomment": "abc"},
                {"thecomment": "def"},
                {"thecomment": "ghi"},
            {"thecomment": "jkl"}
        ]
    }

///////////////// 回答后编辑 /////////////////

这是我用来调用 PHP 函数的 index.php 文件中的 ajax(在其单独的文件中):

    function commentSaveAction ()
    {
        var mytext = $(".mycommentinput").val();
        mytext = mytext.replace("\"","'");

            $.ajax({
                url: 'php/commentwrite.php',
                data: { thePhpData: mytext },
                success: function (response) {
               }
            });
    }

这是我在 deceze 的帮助下使用的完成的 PHP 函数:

    <?php

    function writeFunction () 
    {
        $filename = '../database/comments.txt';

        $arr = json_decode(file_get_contents($filename),true);
        $myData = $_GET['thePhpData'];  

        $arr['commentobjects'][] = array('thecomment' => $myData);
        $json = json_encode($arr);

        $fileWrite=fopen($filename,"w+");
        fwrite($fileWrite,$json);
        fclose($fileWrite);
    }
    writeFunction ();   

    ?>

//////////////////// 使用 JS 而不是 PHP //////////////////////p>

        var myJsonData;

        function getCommentData ()
        {
            $.getJSON('database/comments.txt', function(data) {

                myJsonData = data;

                var count = data.commentobjects.length;
                for (i=0;i<count;i++) {
                    $(".commentbox ul").append("<li>"+data.commentobjects[i].thecomment+"</li>");
                }
            }); 
        }

        function commentSaveAction ()
        {
            var mytext = $(".mycommentinput").val();
            mytext = mytext.replace("\"","'");

            myJsonData.commentobjects.push({"thecomment": mytext});

            var count = myJsonData.commentobjects.length;
            $(".commentbox ul").append("<li>"+myJsonData.commentobjects[count-1].thecomment+"</li>");
        }

【问题讨论】:

    标签: php javascript html json


    【解决方案1】:

    无论您使用哪种语言,您都必须将 JSON 字符串解析为对象/数组,对其进行修改,然后将其编码回 JSON 字符串。不要尝试对 JSON 字符串进行任何直接的字符串操作。 PHP 示例:

    $arr = json_decode($json, true);
    $arr['commentobjects'][] = array('thecomment' => 'jkl');
    $json = json_encode($arr);
    

    是否在 Javascript 或 PHP 或其他地方执行此操作取决于您何时/为什么/在何处需要执行此操作;如果不了解用例的更多信息,这是不可能说的。

    【讨论】:

    • 如果你使用 javascript,你不需要做任何事情......这就是 json 的美妙之处,它对 js 友好!
    • @Ziarno 如果你从 AJAX 调用中收到 JSON 字符串作为 JS 中的字符串,你仍然需要解析它。
    • 是的,这是真的,但是 jQuery 会自动检测到它是 json 并为您执行此操作。此外,问题中没有关于 ajax 的内容。
    • @Ziarno 当然,只是说它在 Javascript 中也不是完全自动的。 :)
    【解决方案2】:

    尝试使用json_encodejson_decode PHP 函数。

    //work on arrays in php
    $arr = array('sth1', 'sth2');
    
    //here you have json
    $jsonStr = json_encode($arr);
    
    //array again
    $arrAgain = json_decode($jsonStr);
    
    $arrAgain[] = 'sth3';
    //json again
    $jsonAgain = json_encode($arrAgain)
    

    【讨论】:

      【解决方案3】:

      只需在 javascript 中执行:

      var x = {"commentobjects": 
          [
                  {"thecomment": "abc"},
                  {"thecomment": "def"},
                  {"thecomment": "ghi"}
          ]
      };
      
      x.commentobjects.push({"thecomment": "jkl"});
      

      【讨论】:

      • 您的回答效果很好。仅使用变量效果很好。我正在使用一个对象,它给了我(对象对象)问题。
      【解决方案4】:
      var THISNEWCOMMENT = 'jkl',
          myObj = JSON.parse(rawJson),
          newComment = {"thecomment": THISNEWCOMMENT};
      myObj.commentobjects.push(newComment);
      var serialized = JSON.stringify(myObj);
      //send the updated JSON to your controller
      

      解析对象,访问其中的commentobject列表,将新评论推送到列表中,然后再次序列化更新的对象。

      【讨论】:

        猜你喜欢
        • 2011-01-15
        • 2021-11-12
        • 1970-01-01
        • 2016-12-23
        • 2022-08-20
        • 1970-01-01
        • 2018-10-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多