You have to be clear on what you mean by "JSON".
Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]
. This one happens to be an array. If you want to add a new element to the array, just push
it, as in
var arr = [{a: 1}];
arr.push({b: 2});
< [{a: 1}, {b: 2}]
The word JSON may also be used to refer to a string which is encoded in JSON format:
var json = '[{"a": 1}]';
请注意表示这是一个字符串的(单)引号.如果您有一个从某处获得的字符串,则需要首先使用JSON.parse
将其解析为JavaScript对象:
var obj = JSON.parse(json);
现在,您可以随心所欲地操纵对象,包括如上所示的push
个.如果您随后希望将其放回JSON字符串中,则使用JSON.stringify
:
var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'
JSON还被用作格式化数据的常用方式,以便在服务器之间传输数据,并在服务器上保存(持久化).这就是ajax的用武之地.Ajax用于从服务器获取数据(通常为JSON格式),和/或向服务器发送JSON格式的数据.如果您收到来自JSON格式的ajax请求的响应,您可能需要如上所述对其进行修改.然后,您可以操作该对象,使用JSON.stringify
将其重新转换为JSON格式,并使用另一个ajax调用将数据发送到服务器进行存储或其他操作.
You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.
Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?