简体   繁体   中英

Creating ordered JSON string from JS object

var data = {};
$('.table-row').each(function(i, el) {
   var key = $(el).find('.key').val();
   var value = $(el).find('.value').val();
   data[key] = value ;
}
var json = JSON.stringify(data);
// output unordered JSON string, since associative object does not preserve order
console.info(json);

How to create ordered JSON string where keys are ordered in insertion order?

For example, when table-row contains elements in following order - a, x, c I need receive JSON string like this {a: 1, x:2, c: 'value001'}

If table-row is an object, element order in table-row is not guaranteed. Does JavaScript Guarantee Object Property Order?

You might be better off starting with an array or MAP to store your keys ordered, which will make it easier to convert to a JSON string of the same order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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