【问题标题】:Javscript store data from json file into map?Javascript将json文件中的数据存储到地图中?
【发布时间】:2020-10-11 09:52:19
【问题描述】:

我对 Javascript 很陌生,但对 Java 了解很多。我试图通过做一些小项目来学习基础知识,以了解语言和代码。在 Java 中,我经常将地图中的数据存储在 json 文件中,当您启动程序时,json 文件会将数据加载到地图中。

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。我的地图是这样的:

var price= new Map();

像上面的Java示例一样,我想将这样的Map加载到json文件中,并希望将json文件中的数据加载到我的map中。

谁能给我一个很好的代码示例,如何在我的地图中存储来自 json 的数据?即使是教程的链接也很棒!

【问题讨论】:

  • Java 不是 JavaScript。一个人的知识不会总是转移到另一个人身上。我知道您实际上并没有说它们是,但值得重申。
  • @evolutionxbox 我知道,这就是我问的原因?
  • 对不起,我澄清你没有这么说。

标签: javascript java json


【解决方案1】:

在 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');

您的价格图(intClient)如下所示:

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

现在,您可以将其序列化为 json:

const json = JSON.stringify(price);

或者从json中解析:

const price = JSON.parse(json);

但是,如果您真的想使用Map,这里有一个tutorial

【讨论】:

    猜你喜欢
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多