Destroy JSON with irregular content

I have an example below where 2 "unusual" things can happen:

  • if status NOK

    , item data

    won't be included at all
  • some element attributes list

    may be missing internally (in the example below, key2

    missing in the second element list

    .

Is there a way to de-serialize an invalid JSON string using automatic output? What's the easiest / best way to deal with this irregular JSON in Rust? Can I avoid writing very complex based code match

to test all possible combinations?

extern crate serialize;

static JSON: &'static str  = r#"
    {
        "status": {
            "status": "OK"
        },
        "data": {
            "container": {
                "key": "value",
                "list": [
                    {
                        "key1": "value1",
                        "key2": "value2"
                    },
                    {
                        "key1": "value1"
                    }
                ]
            }
        }
    }"#;
#[deriving(Decodable, Show)]
struct Top {
    status: Status,
    data: Data,
}

#[deriving(Decodable, Show)]
struct Data {
    container: Container,
}

#[deriving(Decodable, Show)]
struct Status {
    status: String,
}

#[deriving(Decodable, Show)]
struct Container {
    key: String,
    list: Vec<KeyVals>,
}

#[deriving(Decodable, Show)]
struct KeyVals {
    key1: String,
    key2: String,
}

fn main() {
    let result: Top = match serialize::json::decode(JSON) {
        Ok(x) => x,
        Err(why) => fail!("Failed decoding the JSON! Reason: {}", why),
    };
    println!("{}", result);
}

      

When running the code, it fails because the attribute is missing in the second list item key2

.

task '<main>' failed at 'Failed decoding the JSON! Reason: MissingFieldError(key2)', hello.rs:56

      

thank

+3


source to share


1 answer


Potentially existing data can be represented through enumeration. In the simplest case with Option

.

I believe using an enum will solve your problem as well.



#[deriving(Encodable, Decodable)]
enum Status {
    Good(Container),
    Bad,
    VeryBad
}

      

If the Container also contains potentially existing data, you can use an enum again to represent that.

+3


source







All Articles