我对 Javascript 很陌生,但对 Java 了解很多。我试图通过做一些小项目来学习基础知识,以理解语言和代码。在 Java 中,我做了很多工作,将 map 中的数据存储在 json 文件中,当您启动程序时,json 文件将数据加载到 map 中。
Java 示例:
public Map<Integer, Client> example = new HashMap<>();
这里是客户端类:
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;
}
}
我想做同样的事情,但现在是在 Javascript 中。我的 map 如下所示:
var price= new Map();
就像上面的Java示例一样,我想将这样的Map加载到json文件中,并希望将json文件中的数据加载到我的map中。
有人可以为我提供一个很好的代码示例,如何在我的 map 中存储来自 json 的数据吗?即使是教程的链接也很棒!
最佳答案
在 JS 中,更常见的是使用普通对象而不是 Map()
。
例如,假设您有相同的 Client
类:
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');
您的价格图(int
到 Client
)如下所示:
const price = {
1: client1,
2: client2
};
现在,您可以使用将其序列化为 json:
const json = JSON.stringify(price);
或者从json解析它:
const price = JSON.parse(json);
但是,如果您确实想使用Map
,这里有一个 tutorial为了它。
关于javascript - Javascript 将 json 文件中的数据存储到 map 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64302691/