且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从现有的JSON文件添加新的JSON

更新时间:2023-12-02 21:34:16

在编写之前,您需要阅读JSON,将其解析为JS对象,编辑该对象并转换回JSON:

You need to read your JSON, parse it into a JS object, edit the object, and convert back into JSON before writing:

假设myfile.json包含: {"Home":["a","b","c"]}

assuming myfile.json contains: { "Home": [ "a", "b", "c" ] }

$.getJSON('myfile.json', function(data) {
    alert("success");
    obj = JSON.parse(data);
    obj.log = 1;
    writeJSON(JSON.stringify(obj));
}.error(function(data){
    alert(JSON.stringify(data));
});

和writeJSON将类似于:

and writeJSON will be something like:

function writeJSON(jsonString)
    $.ajax({
        type: 'POST',
        url: 'myfile.json',
        data: jsonString,
        success: function(data) { alert('write succesful!'); },
        contentType: "application/json",
        dataType: 'json'
    });
}

假设您使用的服务器可以通过此端点进行读写.

assuming that you are using a server which can both read and write via this endpoint.