javascript 如何将 JSON 存储在变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18443982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:57:11  来源:igfitidea点击:

How to store JSON in a variable

javascriptjqueryjson

提问by Joshna Gunturu

How to store data as JSON like a database, so that when a user registers the information should be stored in a variable?

如何像数据库一样将数据存储为JSON,以便用户注册时将信息存储在变量中?

Example:

例子:

My HTML form consists of input text fields firstname, lastname. Clicking the register button of the form should store the values of firstname and lastname in a variables.

我的 HTML 表单由输入文本字段名字、姓氏组成。单击表单的注册按钮应该将 firstname 和 lastname 的值存储在变量中。

How can I do this:

我怎样才能做到这一点:

 var txt = '{"employees":[' +
   '{"firstName":"John","lastName":"Doe" },' +
    '{"firstName":"Anna","lastName":"Smith" },' +
     '{"firstName":"Peter","lastName":"Jones" }]}';

采纳答案by rainer zufall

Easily use Jquery

轻松使用Jquery

var jsonArray;
jsonArray.push($("#firstname").val();
jsonArray.push($("#lastname").val();
var myJsonString = JSON.stringify(jsonArray);

回答by Paul S.

Sounds like you want to go from values in HTMLto a JSONstring. Assuming <form>looks like this

听起来您想将HTML中的值转换为JSON字符串。假设<form>看起来像这样

<form>
    <input type="text" name="nm1[]"/><input type="text" name="nm2[]"/>
    <input type="text" name="nm1[]"/><input type="text" name="nm2[]"/>
</form>

You can use getElementsByNametwice, build an Objectand JSON.stringifyit

您可以使用getElementsByName两次,构建一个对象,然后JSON.stringify

var nm1 = document.getElementsByName('nm1[]'),
    nm2 = document.getElementsByName('nm2[]'),
    i, o = {
        employees: []
    };
for (i = 0; i < nm1.length; ++i) {
    if (nm1[i].value && nm2[i].value)
        o.employees.push({
            firstName: nm1[i].value,
            lastName: nm2[i].value
        });
}
JSON.stringify(o);

DEMO(open console)

DEMO(打开控制台)

回答by cars10m

You can add data to the actual data structure by appending it to the employeesarray like

您可以通过将数据附加到employees数组来将数据添加到实际数据结构中

dataobj.employees.push({"firstName":$('input[name=firstn]').val(),
                        "lastName":$('input[name=lastn]').val() });

Of course, this requires that the JSON was parsed into the dataobj in the first place. It must be serialized again if you want to send it by GET. But it can be POSTed directly as a data object!

当然,这首先需要将 JSON 解析为 dataobj。如果您想通过GET. 但是可以POST直接作为数据对象进行编辑!

You can of course also start with an empty array, initializing dataobj like

你当然也可以从一个空数组开始,像初始化 dataobj 一样

var dataobj={ employee: [] };

before the above uptdating command comes into action.

在上述更新命令生效之前。

A very lateedit ...

一个很晚的编辑...

Just in case there should be multiple firstname / lastname input fields, then the following will do a "much better" job (as it will have a look at all fields and collect only those where at least one of the names is set):

以防万一应该有多个名字/姓氏输入字段,那么以下将做“更好”的工作(因为它将查看所​​有字段并仅收集那些至少设置了一个名称的字段):

var dataobj={employees:[]};
function shw(){
  $('#out').text(JSON.stringify(dataobj).replace(/{/g,'\n{'));}
$(function(){
  $('#clr').click(function(){dataobj.employees=[];shw()});
  $('#go').click(function(){
   var ln=$('input[name=lastn]').toArray();     // ln: JS-Array of DOM elements
   $('input[name=firstn]').each(function(i,fn){ // for each fn DOM-element ...
    var f=fn.value,l=ln[i].value;               // get values as strings
    if (f+l>'') dataobj.employees.push({firstName:f,lastName:l}); // push name object
   });shw();})
  shw();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="firstn" value="John"><input type="text" name="lastn" value="Doe"><br>
<input type="text" name="firstn" value="Anna"><input type="text" name="lastn" value="Smith"><br>
<input type="text" name="firstn" value="Peter"><input type="text" name="lastn" value="Jones">
<input type="button" id="go" value="append names">
<input type="button" id="clr" value="clear">
<pre id="out"></pre>

回答by GLES

You can use the pushmethod of array to push JSON data. This is shown here - appending-to-a-json-object. Before the data needs to be submitted (say to process.php), stringifyit.

您可以使用push数组的方法来推送 JSON 数据。这在这里显示 -附加到 a-json-object。在需要提交数据之前(比如process.php),将其字符串化