How to parse JSON string but keep the order of the dynamic keys?
Following @RobertAKARobin advice, I get the response of the axios get request as a raw string by setting the responseType : 'arraybuffer'
and transformResponse :undefined
. Then I captured the result in a Buffer which allowed me to view the response as a raw string. Then I used regex to find each occurrence of the key and replaced it with a running count (i). Then I called JSON.parse() which parses the object without sorting which is just what I wanted.
Here is the code.
const cleanSegmentsResult = result => {
const b = new Buffer(result.data,'binary');
const str = b.toString();
const regexp = /"(\d{9})"/;
// replace each 9 digit number (the keys to each segment) with a random key.
// This prevents JSON.parse from sorting the keys and messing with the segments
let i = 0;
let prev = str;
let running_str = '';
while(prev.match(regexp) != null){
running_str = prev.replace(regexp,`\"key${i}\"`);
prev = running_str;
i++;
}
const final_segments = JSON.parse(running_str)
return final_segments;
}
Parsing a JSON string while preserving the original order of keys
As stated by CD.., an object is an unordered collection of properties.
You have at least two options:
you can use arrays instead of objects
you can iterate over the array and print/use the properties from the objects in chosen order easily by using their names.
var a = $.parseJSON(data.Parameters);
for (var i = 0, ilen = a.length; i < ilen; i += 1) {
console.log(a[i].Date);
console.log(a[i].FaultList);
// etc
}
Is the order of elements in a JSON list preserved?
Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format
(emphasis mine):
An object is an unordered collection of zero or more name/value
pairs, where a name is a string and a value is a string, number,
boolean, null, object, or array.An array is an ordered sequence of zero or more values.
The terms "object" and "array" come from the conventions of
JavaScript.
Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.
How to maintain order when parsing JSON from Javascript?
Use an array if you want to keep the order. That should be the only way to maintain the order in javascript.
Keep the order of the JSON keys during JSON conversion to CSV
Solved.
I used the JSON.simple library from here https://code.google.com/p/json-simple/ to read the JSON string to keep the order of keys and use JavaCSV library from here http://sourceforge.net/projects/javacsv/ to convert to CSV format.
Python json.loads changes the order of the object
Dictionaries (objects) in python have no guaranteed order. So when parsed into a dict
, the order is lost.
If the order is important for some reason, you can have json.loads
use an OrderedDict
instead, which is like a dict
, but the order of keys is saved.
from collections import OrderedDict
data_content = json.loads(input_data.decode('utf-8'), object_pairs_hook=OrderedDict)
Related Topics
Calculate Total Sum of Dynamically Added Items to a Table
How to Synchronize the Scroll Position of Two Divs
How to Use Zindex in React-Native
How to Refresh Select Option List After Ajax Response
Error Ts2739: Type '{}' Is Missing the Following Properties from Type
Whenever I Click Outside the Element It Should Close
How to Create a Remember Me Function in Login Without Using Form in JavaScript or Jquery
How to Close Bootstrap 3 Dropdown When We Click Outside on a Tablet
Replace Multiple Strings With Multiple Other Strings
Sort Json Data Based on Date and Time
How to Find If a Text Contains Url String
Reverse Strings Without Changing the Order of Words in a Sentence
How to Clear All Input Fields in Bootstrap Modal When Clicking Data-Dismiss Button
Button Enabled and Disabled Based on Checkbox Is Checked or Not
How to Add Query String Parameter to Same Url When on Click a Href Link