首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >以编程方式向JSON添加数据的最简单方法是什么?

以编程方式向JSON添加数据的最简单方法是什么?
EN

Stack Overflow用户
提问于 2013-07-11 15:25:15
回答 4查看 338关注 0票数 1

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

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

代码语言:javascript
运行
复制
 var myObject = new Object();
 JSON.stringify()
 JSON.parse()
 $.extend();
 .push()
 .concat()

我已经加载了这个JSON文件

代码语言:javascript
运行
复制
    {"commentobjects": 
        [
                {"thecomment": "abc"},
                {"thecomment": "def"},
                {"thecomment": "ghi"}
            ]
    }

我想以编程方式添加

代码语言:javascript
运行
复制
    var THISNEWCOMMENT = 'jkl;
    {"thecomment": THISNEWCOMMENT}

因此,JSON变量将是

代码语言:javascript
运行
复制
    {"commentobjects": 
        [
                {"thecomment": "abc"},
                {"thecomment": "def"},
                {"thecomment": "ghi"},
            {"thecomment": "jkl"}
        ]
    }

/

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

代码语言:javascript
运行
复制
    function commentSaveAction ()
    {
        var mytext = $(".mycommentinput").val();
        mytext = mytext.replace("\"","'");

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

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

代码语言:javascript
运行
复制
    <?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 ();   

    ?>

/

代码语言:javascript
运行
复制
        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>");
        }
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-07-11 15:28:58

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

代码语言:javascript
运行
复制
$arr = json_decode($json, true);
$arr['commentobjects'][] = array('thecomment' => 'jkl');
$json = json_encode($arr);

是否在Javascript、PHP或其他地方执行此操作取决于您需要执行此操作的时间/原因/位置;如果不了解更多的用例,就不可能这么说。

票数 4
EN

Stack Overflow用户

发布于 2013-07-11 15:30:19

尝试使用json_encodejson_decode PHP函数。

代码语言:javascript
运行
复制
//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)
票数 1
EN

Stack Overflow用户

发布于 2013-07-11 16:04:42

只需使用javascript即可:

代码语言:javascript
运行
复制
var x = {"commentobjects": 
    [
            {"thecomment": "abc"},
            {"thecomment": "def"},
            {"thecomment": "ghi"}
    ]
};

x.commentobjects.push({"thecomment": "jkl"});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17587416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档