简体   繁体   English

如何在 Rust 中加载 JSON?

[英]How do I load JSON in Rust?

I want to initialize a Rust variable with a literal.我想用文字初始化 Rust 变量。

Shepmaster guesses that Rust has no map literal because: Shepmaster 猜测Rust 没有 map 文字,因为:

the fact that there are multiple data structures that act maplike (such as both BTreeMap and HashMap) would make it hard to pick one.事实上,有多种数据结构可以像 map 一样(例如 BTreeMap 和 HashMap),这样就很难选择一个。

But Rust says "you should probably just use Vec or HashMap" , meaning that if they are good enough for most purposes, then using them when initializing from a string should usually work just fine.但是 Rust 说“您可能应该只使用 Vec 或 HashMap” ,这意味着如果它们对于大多数用途来说足够好,那么在从字符串初始化时使用它们通常应该可以正常工作。

The example map initialization is clumsy, but printing it produces the JSON-like string:示例 map 初始化很笨拙,但打印它会产生类似 JSON 的字符串:

{"Mars": 1.5, "Mercury": 0.4, "Earth": 1.0, "Venus": 0.7} . {"Mars": 1.5, "Mercury": 0.4, "Earth": 1.0, "Venus": 0.7}

fn main() {
use std::collections::HashMap;

let solar_distance = HashMap::from([
    ("Mercury", 0.4),
    ("Venus", 0.7),
    ("Earth", 1.0),
    ("Mars", 1.5),
]);

println!("{:?}", solar_distance)
}

It shouldn't be technically impossible to create a Rust collection from a string literal (perhaps with syntactic sugar to avoid quote-escape hell) or by loading a JSON file, using the recommended types for arrays and objects:从字符串文字(可能使用语法糖以避免引号转义地狱)或通过加载 JSON 文件创建 Rust 集合在技术上应该不是不可能的,使用 ZA3CBC3F9D0CE2F2C19C54E1 和对象的推荐类型:

fn main() {
use std::collections::HashMap;

let x = String::from("{'Venus': 0.7, 'Mars': 1.5, 'Mercury': 0.4, 'Earth': 1.0}");
println!("{:?}", x);

let solar_distance = HashMap::from(x);
println!("{:?}", solar_distance);
}

This fails with:这失败了:

    |
7   | let solar_distance = HashMap::from(x);
    |                      ^^^^^^^^^^^^^ the trait `From<String>` is not implemented for `HashMap<_, _, _>`

So: since Rust already apparently has JSON dumps built in, has anyone written a JSON loads library?所以:既然 Rust 显然已经内置了 JSON 转储,有没有人写过 JSON 加载库?

If you want to be able to initialize a HashMap concisely (similar to vec![] ), take a look at https://crates.io/crates/hmap .如果您希望能够简洁地初始化HashMap (类似于vec![] ),请查看https://crates.io/crates/hmap It does basically exactly what you're describing.它基本上完全符合您的描述。

If you want to work with serde_json , you can use the json!() macro provided by that library:如果要使用serde_json ,可以使用该库提供的json!()宏:

let x = json!({
  "foo": "bar",
  "baz": [1, 2, 3],
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM