Stop JSON.parse from shuffling the order of an object

When working on my web application, I retrieve a JSON string from the server and store it in a variable called greetings:

var greetings = '{"2":"hoi","3":"hi","1":"salam"}'

I have observed that the greetings begin with index 2 and value hoi. After attempting to parse the JSON, I noticed the following result:

JSON.parse(greetings) // {1: "salam", 2: "hoi", 3: "hi"}

The order of the elements has changed. It appears that JSON.parse organizes the output based on the keys.

Is there a method to maintain the original ordering of the string?

Answer №1

{
   "2":"hello",
   "3":"hey",
   "1":"hi there"
}

This is not an array; it's actually an object. Objects do not follow any specific order. If maintaining a particular sequence is important, consider using a real array instead.

Answer №2

When dealing with objects, it is important to note that the order of indices cannot be relied upon. It is recommended to use an array of key/value pairs instead.

The keys in objects are usually parsed as numeric indices, resulting in an ordered sequence. One workaround for this behavior is to prefix your keys and then remove those prefixes later:

console.log(JSON.parse('{"i2":"hoi","i3":"hi","i1":"salam"}'))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes the state hook in react to alter every single property within the object?

I have a list of team members and each member is associated with the same set of applications. I created 2 classes to link each member with their respective applications, resulting in a comprehensive list of all members and applications. This list was init ...

What steps should I take to fix the error message "Uncaught TypeError: Class constructor m must be called with 'new'" that occurs while attempting to access a polymer v2.0 application?

Is there a way to resolve this error that occurs when attempting to open a Polymer v2.0 app on Safari in iOS? Uncaught TypeError: Class constructor m cannot be invoked without 'new' from custom-elements-es5-adaptor. The Polymer v2.0 starter k ...

Library for Nodejs that specializes in generating and converting PDF/A files

Is there a library available that can convert/create a PDF/A file? I've been searching for solutions but the existing answers suggest using an external service or provide no response at all. I heard about libraries in other languages like ghostscriptP ...

adjust variable increment in JavaScript

As I work on developing a Wordpress theme, I have encountered an issue with incrementing a load more button using Javascript. This is my first time facing this problem with a javascript variable, as I don't always use Wordpress. The variable pull_page ...

Activate JavaScript functions by pressing the enter key, allowing for various searches, AJAX requests, and DataTable displays to occur seamlessly without the need to refresh

I recently developed a web page that integrates an AWS API interface to interact with an RDS Aurora MySQL Serverless database. Users can input a SQL statement and click the Query button, which triggers an AJAX request, returns JSON data, and converts the d ...

Importance of value attribute in <input ng-model ..>

Maybe a silly inquiry, but I'm curious about the purpose of having value="" in this particular situation: <input ng-model="something.name" value="" class="input-xlarge" /> Are there any alternatives to keeping the value attribute empty? I init ...

Creating a pie chart with a legend in the realm of the dojo

Apologies for any language errors. I am looking to develop a web application where users can fill out a form and submit it to the server. The server will then respond with the requested data in JSON format. Using this data, I want to create a diagram and ...

Why is it that the HttpClient constructor in Angular doesn't require parameters when instantiated through the constructor of another class, but does when instantiated via the 'new' keyword?

I am trying to create a static method for instantiating an object of a class, but I have encountered a problem. import { HttpClient } from '@angular/common/http'; export MyClass { // Case 1 public static init(): MyClass { return this(new ...

In HTML, adjust column widths for multiple tables according to the widest column present in any of them

With Python, I am creating an HTML page that contains multiple tables with the same number of columns, all holding the same type of data. While the generated page is functional, I would like to improve readability by ensuring that all tables have the same ...

What is the best way to trigger a snackbar notification when two passwords do not match?

I'm currently developing a full stack application and I am facing an issue with displaying a snackbar in my signup component when the user's password and confirm password do not match. I have been advised to pass the setOpenAlert method as props ...

Converting a class to a JSON object with ArraySegment

I am currently grappling with a particular issue, I am aiming to transfer a Json object using ArraySegment my JSON Data conforms to this structure {"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, ...

The current situation is not effective; it is causing an error saying "Uncaught TypeError: Cannot read property 'substring' of undefined"

Encountering an error "Uncaught TypeError: Cannot read property 'substring' of undefined" while debugging in Chrome Inspector, with the following code: <script type="text/javascript"> $(function countComments() { var mcount = '/ ...

Implement a mandatory parameter in the URL route using ui-router

My Angular routing configuration using ui-router is quite simple: $stateProvider .state("master", { abstract: true, url: "/{tenantName}" }) .state("master.home", { url: "", }) .state("master.login ...

The range slider's color value is not resetting correctly when using the <input>

Before repositioning, the slider is at this location: (both thumb and color are correctly positioned) https://i.stack.imgur.com/J3EGX.png Prior to Reset: Html <input id="xyzslider" class="mdl-slider mdl-js-slider" type="range" min="0.0" max="1.0" va ...

"Exploring Angular: A guide to scrolling to the bottom of a page with

I am trying to implement a scroll function that goes all the way to the bottom of a specific section within a div. I have attempted using scrollIntoView, but it only scrolls halfway down the page instead of to the designated section. .ts file @ViewChild(" ...

Hiding a specific tag with vanilla JavaScript based on its content

I am facing a challenge with my code that is supposed to hide div elements containing a specific word along with additional text. I have tried multiple solutions but none seem to work effectively. Any assistance on how to hide divs properly will be greatl ...

Unable to convert the array token into an instance of the model class

I'm currently attempting to send a JSON array list to a Spring REST endpoint and implementing my logic as shown below: Model Class : public class ABCDEF{ private String A; private String B; private ArrayList<Long> C; private ArrayList<Long ...

Begin the Wordpress AJAX Login

Is there a way to trigger the code below when a user is logged out from another location due to user inactivity, similar to how wp-admin displays an AJAX login overlay if a user is logged out? I have not come across any documentation or tutorials on achiev ...

Square Division, width set to match 100% of the height

I have been attempting to create a square shape that is responsive, with the width determined by the height of the element (100%). I personally think achieving this using CSS alone is not possible. The goal is for the square's width to match its heig ...