JavaScript JSON Data response incorrect position json data response example,json data response,json data response

I have a function to call API from the server like this:

 getDataSet(callback) {
            request.open('POST', `${apiPath}`);
            request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            request.onreadystatechange = function () {
                if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
                    return callback(null, JSON.parse(request.responseText));
                }
            };
            request.send();
        }

 dataSetDetail.getDataSet((err, response) => {
        if (err) return (console.log(err));
        if (response.success) {
            let data = response.data.dataSetDetails.slice(0, 10);
        }
    });

and here is server side:

router.post('/:projectid/data/:id', isAuthenticated, (req, res, next) => {
    let dataSetId = parseInt(req.params.id);
    dataSet.getDataSet(dataSetId)
        .then(dataSet => {
            if (!lodash.isNull(dataSet)) {
                res.setHeader('Content-Type', 'application/json');
                return res.json({
                    data: dataSet,
                    success: true,
                });

            } else {
                logger.error('Cannot find data set with id: ' + dataSetId);
                res.redirect('../data');
            }
        })
        .catch(e => {
            logger.error(e);
            res.redirect('../data');
        })

});

The response from the server is:

[
  {
    "left": "2",
    "right": "3",
    "operator": "+"
  },
  {
    "left": "6",
     "right": "4"
    "operator": "-"
  }
]

but in the client side I received the result sometimes like server side, sometimes like below :

[
      {
        "operator": "+",
        "right": "3",
        "left": "2",

      },
      {
        "operator": "-",
        "right": "4",
        "left": "6"
      }
    ]

Because I need to display the correct data position on UI. Please give me advice

Answer:1

Two options for you:

1. Use an array

JSON object notation has no order. From http://json.org:

An object is an unordered set of name/value pairs.

(My emphasis.)

Although JavaScript objects have an order now (as of ES2015), using it is usually not best practice.

If you need order, and particularly if you need to preserve order through JSON, use an array:

[
    ["2", "3", "+"],
    ["6", "4", "-"]
]

If you need the property names, send them too:

{
    names: ["left", "right", "operator"],
    data:  [
        ["2", "3", "+"],
        ["6", "4", "-"]
    ]
}

I strongly recommend this over Option 2.

2. Ensure you create dataSet in the correct order

If you're dead set on using an object and relying on property order (not recommended), and you're using JavaScript at both ends (as you seem to be), and your properties on dataSet are "own" properties (not inherited) and they don't have integer index names (your example ones don't), then:

Ensure you create the objects in dataSet in the order you want the properties serialized, e.g.:

const dataSet = [];
dataSet.push({
    left: "2",
    right: "3",
    operator: "+"
});

or

const dataSet = [];
let entry = {};
entry.left = "2";
entry.right = "3";
entry.operator = "+";
dataSet.push(entry);
// ...

Not

const dataSet = [];
let entry = {};
entry.operator = "+";  // *** These are
entry.right = "3";     // *** in the
entry.left = "2";      // *** wrong order
dataSet.push(entry);
// ...

Don't use for-in or Object.keys, they aren't specified to follow property order. If you need an array of property names in order, use Object.getOwnPropertyNames.

The properties will be in the order you want, JSON.stringify is specified to follow that order, and JSON.parse is specified to create objects with them in that order in the result. So even though JSON doesn't guarantee order, JavaScript's JSON.stringify and JSON.parse do in very limited contexts.

Again, though: Not recommended.

but in the client side I received the result sometimes like server side, sometimes like below

It's more likely that what the server sends varies (perhaps based on branches in the code), and it happens you just looked at one with the order you want. If the server sends the JSON you've shown, JSON.parse will preserve that order (see above for why).

Answer:2

I have a JSON structure like this: [ {"menuId":"1001","depth":"1","parentId":"0"}, {"menuId":"1002","depth":"1","parentId":"0"}, {"menuId":"1003","depth":"2","parentId":"1001"}, {"...

I have a JSON structure like this: [ {"menuId":"1001","depth":"1","parentId":"0"}, {"menuId":"1002","depth":"1","parentId":"0"}, {"menuId":"1003","depth":"2","parentId":"1001"}, {"...

I'm trying to write a mocha test which passes on a stream error but fails if the stream ends without an error. Detecting the error is no problem, but the finish handler is always called, even if the ...

I'm trying to write a mocha test which passes on a stream error but fails if the stream ends without an error. Detecting the error is no problem, but the finish handler is always called, even if the ...

I'm building a photo gallery in react js. Obviously it's going to have to be responsive and I've tackled this by setting values like so in the component's render method: let thumbWidth = window....

I'm building a photo gallery in react js. Obviously it's going to have to be responsive and I've tackled this by setting values like so in the component's render method: let thumbWidth = window....

  1. change value react
  2. change value react-select
  3. change props value react
  4. change context value react
  5. change input value react
  6. change state value react
  7. change props value react native
  8. change textinput value react native
  9. change ref value react
  10. change state value react native
  11. change animated value react native
  12. change text value react native
  13. change checkbox value react
  14. change value onclick react
  15. change const value react
  16. change array value react
  17. change textarea value react
  18. change context value react hooks
  19. change const value react native
  20. change input value react testing library

We have URL when we hit URL URL in browser we got data. We got Data like [{"UserId":"c2fbd9fb-a423-4d33-9ea4-3aa58f7b52cf","UserType":"Parent","OutPutMessage":"Sucess"}]. But We need get data ...

We have URL when we hit URL URL in browser we got data. We got Data like [{"UserId":"c2fbd9fb-a423-4d33-9ea4-3aa58f7b52cf","UserType":"Parent","OutPutMessage":"Sucess"}]. But We need get data ...