简体   繁体   中英

How to add the new JSON from existing JSON file

I searched here get few related posts found but not helpful. I created one json file it has some text i want to append some more json in that using javascript(JSON stored in locally).

I have json file like this:

{ "Home": [ "a", "b", "c" ] }

i want to include this text "Log": 1

want to achieve like this,

{ "Home": [ "a", "b", "c" ], "Log": 1 }

Now I have like this in my json file(currently i have but json format is not correct)

{ "Home": [ "a", "b", "c" ] } 
{ "Log": 1 }

$.getJSON('myfile.json', function(data) {
    alert("success");
}.error(function(data){
    alert(JSON.stringify(data));
});

this returns parser error . I know the JSON format is wrong. Please guide me to create a correct JSON format.

The error is in both versions of the JSON. You are missing the " at the start of the string c .

http://jsonlint.com/ will help you track down where errors in JSON occur.

As a rule of thumb, you should create JSON using a JSON serializer in a mature library and not by hand or string concatenation.


Now i have like this in my json file

That's completely wrong. The code you had in "Now i want to achieve like this" was right (aside from the error mentioned above).

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

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));
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM