简体   繁体   中英

How can I use the sort function for a Json?

I'm using the code from Sorting an array of objects by property values to sort my Json. But it isn't working, I'm using request to store a Json from a web API and using jsonpath.

It isn't sorting, it's just sending me the GET content (before sort). I feel it's the problem with the parseFloat (line 15), but I am unsure how to fix it. I went into https://jsonpath.com/ to test a bit, and it should be ..rank not .rank

My code:

var request = require('request');
var jp = require('jsonpath');

var options = {
  'method': 'GET',
  'url': 'https://groups.roblox.com/v1/groups/2642914/roles',
  'headers': {
  }
};
request(options, function (error, response) {
  if (error) throw new Error(error);
  var obj = JSON.parse(response.body);
  var rolesList = jp.query(obj, '$..roles');
  rolesList.sort(function(a, b) {
    return parseFloat(a.rank) - parseFloat(b.rank);
});
    console.log(rolesList)
});

.query always returns an array of all matches

Find elements in obj matching pathExpression. Returns an array of elements that satisfy the provided JSONPath expression, or an empty array if none were matched. Returns only first count elements if specified.

You are getting from that jsonpath query rolesList = [ [{... rank: ...}, {}, {}...] ] , so sort is acting on a single element array.

You can use .value instead to get the first match found.

$..roles is unnecessary, unless you need to get arbitrary nested level properties, which is not the case here. It's accessible at the first level.

I've used CORS anywhere so this can be run in the browser ( codesandbox here ):

var request = require('request');
var jp = require('jsonpath');
var options = {
  'method': 'GET',
  'url': 'https://cors-anywhere.herokuapp.com/https://groups.roblox.com/v1/groups/2642914/roles',
  'headers': {
  }
};
request(options, function (error, response) {
  if (error) console.error(error);
  var obj = JSON.parse(response.body);
  var rolesList = jp.value(obj, '$.roles');
  rolesList.sort(function(a, b) {
    return a.rank - b.rank;
  });
  
  console.log(rolesList)
});

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