Javscript store data from json file into map?

Viewed 126

I´m quite new to Javascript, but know a lot about Java. Im trying to learn the basics by doing little projects, for understanding the language and code. In Java, i worked a lot with storing data from maps in json-files and, when you start the programm, the json file loads the data into the map.

An example for Java:

public Map<Integer, Client> example = new HashMap<>();

Herefor the Client class :

public class Client {

private String username;
private String password;
private String host;

public Client(String username, String password, String host) {
    this.username = username;
    this.password = password;
    this.host = host;
}

public String getPassword() {
    return password;
}

public String getHost() {
    return host;
}

public String getUsername() {
    return username;
}
}

I want to do the same thing, but now in Javascript. My map looks like that:

var price= new Map();

Like the Java example above, I want to load such a Map into a json file and want to load the data from the json file into my map.

Could somebody proivde me with a good example of code, how to store data from json in my map ? Even a link for a tutorial would be great!

1 Answers

In JS it's more common to use plain objects instead of Map().
For example, let's say you have the same Client class:

class Client {
    constructor(username, password, host) {
        this.username = username;
        this.password = password;
        this.host = host;
    }
}

const client1 = new Client('username1', 'password1', 'localhost');
const client2 = new Client('username2', 'password2', 'localhost');

Your price map (int to Client) would look like this:

const price = {
    1: client1,
    2: client2
};

Now, you can use serialize it to json:

const json = JSON.stringify(price);

Or parse it from json:

const price = JSON.parse(json);

However, if you really want to use Map, here's a tutorial for it.

Related