我如何从JSON对象转换为元素的形式?

时间:2021-01-14 20:20:28

I have a JSON object as {a: 1, b: 2, c: [4, 5, 6], d: {x: 7, y: 8, z: [9, 0]}}, how do I convert it to a form of elements?

我有一个JSON对象为{a:1,b:2,c:[4,5,6],d:{x:7,y:8,z:[9,0]}},我该如何转换它是一种形式的元素?

I want to convert to this:

我想转换成这个:

<input type="hidden" name="obj[a]" value="1"/>
<input type="hidden" name="obj[b]" value="2"/>
<input type="hidden" name="obj[c][]" value="4"/>
<input type="hidden" name="obj[c][]" value="5"/>
<input type="hidden" name="obj[c][]" value="6"/>
<input type="hidden" name="obj[d][x]" value="7"/>
<input type="hidden" name="obj[d][y]" value="8"/>
<input type="hidden" name="obj[d][z][]" value="9"/>
<input type="hidden" name="obj[d][z][]" value="0"/>

Any ideas?

3 个解决方案

#1


4  

These should do it:

这些应该这样做:

with jQuery

var obj = { a: 1, b: 2, c: [4, 5, 6], d: { x: 7, y: 8, z: [9, 0] } };

function analyzer(o, trail) {
    if (!trail) trail = 'obj';
    for (var n in o) {
        var el = $('<input>', { type: 'hidden' });
        el.attr('name', trail + '[' + n + ']');
        if (typeof o[n] === 'number') {
            el.attr('value', o[n]);
            $('body').append(el);
        } else if (Array.isArray(o[n])) {
            el.attr('name',function(i,v) { return v + '[]'; });
            for (var i = 0; i < o[n].length; ++i) {
                el.clone().attr('value', o[n][i] ).appendTo('body');
            }
        } else {
            analyzer(o[n], trail + '[' + n + ']');
        }
    }
}
analyzer(obj);

JSFIDDLE DEMO

FYI, you can find a compatibility patch for Array.isArray at MDN.

仅供参考,您可以在MDN上找到Array.isArray的兼容性补丁。

Or you can use jQuery.isArray() instead.

或者你可以使用jQuery.isArray()代替。


jQuery reworked

You may prefer this a bit. It doesn't create an element, then clone it in the Array loop, but rather uses a little redundant code to create the elements.

您可能更喜欢这一点。它不会创建一个元素,然后在Array循环中克隆它,而是使用一些冗余代码来创建元素。

function analyzer(o, trail) {
    if (!trail) trail = 'obj';
    for (var n in o) {
        if (typeof o[n] === 'number') {
            $('<input>', { type: 'hidden', name: trail + '[' + n + ']', value: o[n] })
                .appendTo( 'body' );
        } else if (Array.isArray(o[n])) {
            for (var i = 0; i < o[n].length; ++i) {
                $('<input>', { type: 'hidden', name: trail + '[' + n + '][]', value: o[n][i] })
                    .appendTo( 'body' );
            }
        } else {
            analyzer(o[n], trail + '[' + n + ']');
        }
    }
}

JSFIDDLE DEMO


with native DOM API

If you're having any performance issues, use the native API, and cache the DOM selection.

如果您遇到任何性能问题,请使用本机API,并缓存DOM选择。

function analyzer(o, trail) {
    var el;
    if (!trail) trail = 'obj';
    for (var n in o) {
        if (typeof o[n] === 'number') {
            el = document.createElement('input');
            el.type = 'hidden';
            el.name = trail + '[' + n + ']';
            el.value = o[n];
            container.appendChild( el );
        } else if (Array.isArray(o[n])) {
            for (var i = 0; i < o[n].length; ++i) {
                el = document.createElement('input');
                el.type = 'hidden';
                el.name = trail + '[' + n + '][]';
                el.value = o[n][i];
                container.appendChild( el );
            }
        } else {
            analyzer(o[n], trail + '[' + n + ']');
        }
    }
}

JSFIDDLE DEMO

Doesn't require much more code, should work in all typically supported browsers, and should be very fast.

不需要更多代码,应该在所有通常支持的浏览器中工作,并且应该非常快。


native API reworked to shorten

function analyzer(o, trail) {
    var el;
    if (!trail) trail = 'obj';
    for (var n in o) {
        (el = document.createElement('input')).type = 'hidden';
        el.name = trail + '[' + n + ']';
        if (typeof o[n] === 'number') {
            container.appendChild( el ).value = o[n];
        } else if (Array.isArray(o[n])) {
            el.name += '[]';
            for (var i = 0; i < o[n].length; ++i) {
                container.appendChild( el.cloneNode(false) ).value = o[n][i];
            }
        } else {
            analyzer(o[n], trail + '[' + n + ']');
        }
    }
}

JSFIDDLE DEMO

#2


1  

For a quick response -

快速回复 -

Create a function that loops through objects. Use a for in loop to create a string to concatonate these inputs. Test if the value found for each object contains a primitive value, array or object`.

创建一个循环遍历对象的函数。使用for循环创建一个字符串以连接这些输入。测试为每个对象找到的值是否包含原始值,数组或对象`。

E.g. Object.prototype.toString.call(val) === '[object Object]';

例如。 Object.prototype.toString.call(val)==='[object Object]';

If it does, recursively call the function to extract the values from said found object / array

如果是,则递归调用该函数以从所述找到的对象/数组中提取值

#3


1  

Here this does not give the code for creating the HTML, but what it does it create an object with two arrays. One contains the name and the other contains the value. Also, this will work no matter how deeply you nest your objects.

这里没有给出创建HTML的代码,但它创建了一个带有两个数组的对象。一个包含名称,另一个包含值。此外,无论您将对象嵌套多深,这都会有效。

Array.prototype.isArray=true;//Not sure this is the best solution, but it seems to work

function parse(a){
  var b,c,i,obj={
    name:[],
    value:[]
  };
  for(x in a){
    b=a[x];
    if(b.isArray){
      for(i=0;i<b.length;i++){
        obj.name.push('['+x+'][]');
        obj.value.push(b[i]);
      }
    }
    else if(typeof b==='object'){
      var f=x;
      var d=parse(b);
      for(i=0;i<d.name.length;i++){
        d.name[i]='['+f+']'+d.name[i];
      }
      console.log(d.name);
      obj.name.push.apply(obj.name, d.name);
      obj.value.push.apply(obj.value, d.value);
    }
    else{
      obj.name.push('['+x+']');
      obj.value.push(b);
    }
  }
  return obj;
}
console.log(parse({a: 1, b: 2, c: [4, 5, 6], d: {x: 7, y: 8, z: [9, 0]}}));

#1


4  

These should do it:

这些应该这样做:

with jQuery

var obj = { a: 1, b: 2, c: [4, 5, 6], d: { x: 7, y: 8, z: [9, 0] } };

function analyzer(o, trail) {
    if (!trail) trail = 'obj';
    for (var n in o) {
        var el = $('<input>', { type: 'hidden' });
        el.attr('name', trail + '[' + n + ']');
        if (typeof o[n] === 'number') {
            el.attr('value', o[n]);
            $('body').append(el);
        } else if (Array.isArray(o[n])) {
            el.attr('name',function(i,v) { return v + '[]'; });
            for (var i = 0; i < o[n].length; ++i) {
                el.clone().attr('value', o[n][i] ).appendTo('body');
            }
        } else {
            analyzer(o[n], trail + '[' + n + ']');
        }
    }
}
analyzer(obj);

JSFIDDLE DEMO

FYI, you can find a compatibility patch for Array.isArray at MDN.

仅供参考,您可以在MDN上找到Array.isArray的兼容性补丁。

Or you can use jQuery.isArray() instead.

或者你可以使用jQuery.isArray()代替。


jQuery reworked

You may prefer this a bit. It doesn't create an element, then clone it in the Array loop, but rather uses a little redundant code to create the elements.

您可能更喜欢这一点。它不会创建一个元素,然后在Array循环中克隆它,而是使用一些冗余代码来创建元素。

function analyzer(o, trail) {
    if (!trail) trail = 'obj';
    for (var n in o) {
        if (typeof o[n] === 'number') {
            $('<input>', { type: 'hidden', name: trail + '[' + n + ']', value: o[n] })
                .appendTo( 'body' );
        } else if (Array.isArray(o[n])) {
            for (var i = 0; i < o[n].length; ++i) {
                $('<input>', { type: 'hidden', name: trail + '[' + n + '][]', value: o[n][i] })
                    .appendTo( 'body' );
            }
        } else {
            analyzer(o[n], trail + '[' + n + ']');
        }
    }
}

JSFIDDLE DEMO


with native DOM API

If you're having any performance issues, use the native API, and cache the DOM selection.

如果您遇到任何性能问题,请使用本机API,并缓存DOM选择。

function analyzer(o, trail) {
    var el;
    if (!trail) trail = 'obj';
    for (var n in o) {
        if (typeof o[n] === 'number') {
            el = document.createElement('input');
            el.type = 'hidden';
            el.name = trail + '[' + n + ']';
            el.value = o[n];
            container.appendChild( el );
        } else if (Array.isArray(o[n])) {
            for (var i = 0; i < o[n].length; ++i) {
                el = document.createElement('input');
                el.type = 'hidden';
                el.name = trail + '[' + n + '][]';
                el.value = o[n][i];
                container.appendChild( el );
            }
        } else {
            analyzer(o[n], trail + '[' + n + ']');
        }
    }
}

JSFIDDLE DEMO

Doesn't require much more code, should work in all typically supported browsers, and should be very fast.

不需要更多代码,应该在所有通常支持的浏览器中工作,并且应该非常快。


native API reworked to shorten

function analyzer(o, trail) {
    var el;
    if (!trail) trail = 'obj';
    for (var n in o) {
        (el = document.createElement('input')).type = 'hidden';
        el.name = trail + '[' + n + ']';
        if (typeof o[n] === 'number') {
            container.appendChild( el ).value = o[n];
        } else if (Array.isArray(o[n])) {
            el.name += '[]';
            for (var i = 0; i < o[n].length; ++i) {
                container.appendChild( el.cloneNode(false) ).value = o[n][i];
            }
        } else {
            analyzer(o[n], trail + '[' + n + ']');
        }
    }
}

JSFIDDLE DEMO

#2


1  

For a quick response -

快速回复 -

Create a function that loops through objects. Use a for in loop to create a string to concatonate these inputs. Test if the value found for each object contains a primitive value, array or object`.

创建一个循环遍历对象的函数。使用for循环创建一个字符串以连接这些输入。测试为每个对象找到的值是否包含原始值,数组或对象`。

E.g. Object.prototype.toString.call(val) === '[object Object]';

例如。 Object.prototype.toString.call(val)==='[object Object]';

If it does, recursively call the function to extract the values from said found object / array

如果是,则递归调用该函数以从所述找到的对象/数组中提取值

#3


1  

Here this does not give the code for creating the HTML, but what it does it create an object with two arrays. One contains the name and the other contains the value. Also, this will work no matter how deeply you nest your objects.

这里没有给出创建HTML的代码,但它创建了一个带有两个数组的对象。一个包含名称,另一个包含值。此外,无论您将对象嵌套多深,这都会有效。

Array.prototype.isArray=true;//Not sure this is the best solution, but it seems to work

function parse(a){
  var b,c,i,obj={
    name:[],
    value:[]
  };
  for(x in a){
    b=a[x];
    if(b.isArray){
      for(i=0;i<b.length;i++){
        obj.name.push('['+x+'][]');
        obj.value.push(b[i]);
      }
    }
    else if(typeof b==='object'){
      var f=x;
      var d=parse(b);
      for(i=0;i<d.name.length;i++){
        d.name[i]='['+f+']'+d.name[i];
      }
      console.log(d.name);
      obj.name.push.apply(obj.name, d.name);
      obj.value.push.apply(obj.value, d.value);
    }
    else{
      obj.name.push('['+x+']');
      obj.value.push(b);
    }
  }
  return obj;
}
console.log(parse({a: 1, b: 2, c: [4, 5, 6], d: {x: 7, y: 8, z: [9, 0]}}));