简体   繁体   English

JavaScript 中将数组转换为 json 的问题

[英]Problem with converting array to json in JavaScript

I have this code:我有这个代码:

var fields = [];
$('input').each(function(){
  var name = $(this).attr("name");
  fields[name] = $(name).val();
});

And I want convert the fields variable to a json string, but when I use JSON.stringify I get (using console.log ) only: []我想将fields变量转换为 json 字符串,但是当我使用JSON.stringify我只得到(使用console.log ): []

How can I simply convert array fields to a json string?如何简单地将数组fields转换为 json 字符串?

Ok problem was on the following line:好的问题出在以下行上:

 fields[name] = $(name).val();

I changed name to this :我把name改成this

 fields[name] = $(this).val();

And worked like i want it to.并且像我想要的那样工作。

If you want text strings like field names (as opposed to numbers) as property names, you want an object , not an array.如果您想要像字段名称(而不是数字)这样的文本字符串作为属性名称,您需要一个object ,而不是一个数组。 Initialize fields to {} instead of [] .fields初始化为{}而不是[]

The JSON serialization of an array will only include the properties whose keys are numbers, from zero up to the value of .length (minus one).数组的 JSON 序列化将仅包括键为数字的属性,从零到.length (减一)的值。

Just made one correction, use object instead of array:刚刚做了一个更正,使用对象而不是数组:

    var fields = {};
    $('input').each(function(){
     var name = $(this).attr("name");
     fields[name] = $(name).val();
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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