Reputation: 977
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.
Upvotes: 2
Views: 1496
Reputation: 6548
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.
Upvotes: 3
Reputation: 944083
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).
Upvotes: 4