Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode JSON object with Rust keyword attribute name?

Tags:

json

rust

I was wondering if it is possible to decode a JSON object in Rust that has an attribute name which is also a Rust keyword. I am working with the rustc-serialize crate and my struct definition looks like this:

#[derive(RustcDecodable)]
struct MyObj {
  type: String
}

The compiler throws an error because type is a keyword. The exact compiler error message is:

error: expected identifier, found keyword `type`
src/mysrc.rs:23     type: String,
                           ^~~~

Sorry for the rookie question, I have just started trying out Rust.

like image 823
rking788 Avatar asked Mar 17 '15 17:03

rking788


People also ask

What is SerDe JSON?

The Hive JSON SerDe is commonly used to process JSON data like events. These events are represented as single-line strings of JSON-encoded text separated by a new line. The Hive JSON SerDe does not allow duplicate keys in map or struct key names.

How do I parse a JSON file?

If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.

How do you deserialize a JSON string in Python?

To deserialize the string to a class object, you need to write a custom method to construct the object. You can add a static method to ImageLabelCollection inside of which you construct Label objects from the loaded JSON dictionary and then assign them as a list to the class variable bbox.

How do I decode JSON in Golang?

To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct. Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. Note: If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.


1 Answers

You can use the serde crate. It supports renaming of fields since February 2015

Your example could then look like this:

#[derive(Deserialize)]
struct MyObj {
    #[serde(rename = "type")] 
    type_name: String
}
like image 177
oli_obk Avatar answered Sep 21 '22 22:09

oli_obk