0

I just discovered a small problem coming from HttpClient, when I try to fetch data from my api:

constructor(private http: HttpClient) {}
ngOnInit(): void {
    this.http.get("http://localhost:8080/api/test/test?status=None").subscribe((data)=>{
    console.log(data);
})}

It seems to order the json field in alphabetic order. Here is the result from Postman:

"total": {
    "error": 321,
    "run": 338,
    "desc": 1000
}

And here is from Angular HttpClient:

total: {
    desc: 321,
    error: 1000,
    run: 338
}

Did someone have the same issue or just a tip to force HttpClient to not alphabetically order the field?

6
  • In your example the response is ordered in Postman but NOT ordered in HttpClient. Did I miss something? Commented Feb 19, 2024 at 17:15
  • Yeah sorry, it just fake the field. I correct it to match it to my question Commented Feb 19, 2024 at 17:24
  • 1
    Neither result is in order. Also the result from Angular in your question is not in JSON format. Please proofread before posting Commented Feb 19, 2024 at 17:26
  • 3
    this is how browser represents objects passed from json. you should not rely on the order of properties in javacsript objects. ordered collections are for example arrays. on other js engines order of props can theoretically be different, but afaik all popular browsers would make properties go in order Commented Feb 19, 2024 at 18:13
  • 2
    Do NOT rely on the order of an object. Use arrays/iterables instead. Commented Feb 19, 2024 at 20:50

1 Answer 1

1

The order of a JSON object is insignificant.

According to json.org:

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

If you have to depend on the order of an object, then you might want to use an iterable data type like array that can be used in JSON.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.