18

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:

error: expected identifier, found keyword `type`
src/mysrc.rs:23     type: String,
                           ^~~~
3
  • Is it safe to assume that the original data can't be changed to avoid the conflict? Commented Mar 17, 2015 at 17:42
  • yes, it would be best if i didn't have to change the source data. I guess maybe creating a new struct field with a different name and writing a custom impl Decodable is the only way? Commented Mar 17, 2015 at 18:34
  • I can see either manually implementing it or using Json::from_str and then poking into its result value. Commented Mar 17, 2015 at 18:57

2 Answers 2

27

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Seems like exactly what i was looking for. It says it does some lookahead, do you know if it is possible to parse an attribute that could be one of a few different types? so a field called msg could be either a JSON string or an array.
That is one of the main reasons serde was invented, because the old deserializer couldn't read an enum without having read a tag beforehand.
2

This can be done without serde's field renaming by using raw identifiers. By adding r# in front of an identifier, a keyword name can be used.

Using rustc-serialize

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

Using serde

use serde::Deserialize;

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

Note that rustc-serialize is deprecated in favor of serde.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.