0

I have array of objects as sample below. After JSONata evaluation, the order of array of object changes. string with numeric id appears before i.e id 5 appears before id 4a.

How to avoid this change in order

var data = [
    {
        "id": 1,
        "body": "First Item",
        "severity": 1,
        "status": 0
    },
    {
        "id": 2,
        "body": "Second Item",
        "severity": 2,
        "status": 1
    },
{
        "id": 3,
        "body": "third Item",
        "severity": 4,
        "status": 2
    }, 
{
        "id": 4a,
        "body": "four Item",
        "severity": 2,
        "status": 1
    },
{
        "id": 5,
        "body": "five Item",
        "severity": 2,
        "status": 3
    }
]

var result = JSONata(query).evaluate(data)

1

2 Answers 2

0

The Issue is that in your array id parameter contains some non numberic values like 4a. This causes sorting behaviour malfunction and it results in appearing id:5 value before id:4a value

var data = [
    {
        "id": 1,
        "body": "First Item",
        "severity": 1,
        "status": 0
    },
    {
        "id": 2,
        "body": "Second Item",
        "severity": 2,
        "status": 1
    },
    {
        "id": 3,
        "body": "third Item",
        "severity": 4,
        "status": 2
    }, 
    {
        "id": "4a",  // change here to a string
        "body": "four Item",
        "severity": 2,
        "status": 1
    },
    {
        "id": 5,
        "body": "five Item",
        "severity": 2,
        "status": 3
    }
];

var query = "[$]"; // Keeps original order
var result = JSONata(query).evaluate(data);

console.log(result); // check the output

0

Assuming that your JSON input countains an unordered array of objects with an id of either a number or string, such as:

[
  {
    "id": "4a",
    "body": "four Item",
    "severity": 2,
    "status": 1
  },
  {
    "id": 2,
    "body": "Second Item",
    "severity": 2,
    "status": 1
  },
  {
    "id": 1,
    "body": "First Item",
    "severity": 1,
    "status": 0
  },
  /* the rest ... */
]

You can explicitly order them using the Order-by operator in ascending order by casting all ids into string, like so:

$^($string(id))

The resulting JSON will look like:

[
  {
    "id": 1,
    "body": "First Item",
    "severity": 1,
    "status": 0
  },
  {
    "id": 2,
    "body": "Second Item",
    "severity": 2,
    "status": 1
  },
  {
    "id": "4a",
    "body": "four Item",
    "severity": 2,
    "status": 1
  },
  /* the rest */
]

Playground link: https://jsonatastudio.com/playground/c03c086d

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.