2

I have a JSON file (myfile.json) that looks like this:

{"3":["c","d"], "3.5":["j","k"], "1.5":["a","b"], "2.5":["x","y"] } 

What I want to do open the file and sort it using d3.js file opening.

 d3.json('myfile.json',function(err,datafull){ for (var myval in datafull) { console.log(myval); } }); 

Now if I do that, the console.log will print they key in unsorted manner. How can I sort the file?

This is different question, because it involves file parsing.

2
  • 1
    Put each item into an array and then sort the array. Or use Object.keys() to get an array of the keys, sort that array, then use it to access the properties of the original object in sorted order. But you can't sort a (non-array) object. Commented Sep 16, 2015 at 0:29
  • @nnnnnn: How do you put the file into the array? Commented Sep 16, 2015 at 0:37

1 Answer 1

2

To sort object keys you can use Object.keys() method which gives an array of the given objects keys then you can use the array sort() method.

d3.json('myfile.json',function(err,data){ keys = Object.keys(data), i, len = keys.length; keys.sort(function(a, b) { return a - b; }); for (i = 0; i < len; i++) { var a = keys[i]; console.log(a + ':' + data[a]); } } 

See http://jsfiddle.net/sjmcpherso/mvrWb/234/

Sign up to request clarification or add additional context in comments.

8 Comments

how do you store myfile.json to myObj?
Your output is already appears to be an object, is that not the case?
I need to start from input JSON file.
@sjm - note that .sort() with no comparator callback will do a lexical sort, and I suspect the OP wants a numeric sort.
I've updated my answer but that all depends if 'data' is actually an object which I'm guessing it is
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.