uuid-rs / uuid

Generate and parse UUIDs.

Home Page:https://www.crates.io/crates/uuid

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Uuid Serialization & Deserialization Error : expected ident at line 1 column 2

WarrenN1 opened this issue · comments

I have a HashMap<String, String> That is storing data as such:

{'uuid': 'f4a9a11b-6e71-443d-9289-71a26fe6a018'}

When I use:

let data = self.session_data.get("uuid");
if data.is_none()
{
	return 0;
}
let test_uuid: Uuid = serde_json::from_str(data.unwrap().as_str())?;

I get the error:

expected ident at line 1 column 2

And I have no earthly idea why.

Your issue is that a UUID (in JSON) is a string. You can see this if you perform the following test:

let id = uuid!("f4a9a11b-6e71-443d-9289-71a26fe6a018");
let s_id = serde_json::to_string(&id).unwrap();
// This check will fail
assert_eq!(s_id, "f4a9a11b-6e71-443d-9289-71a26fe6a018");

If you run this, you will get the following error:

thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `"\"f4a9a11b-6e71-443d-9289-71a26fe6a018\""`,
 right: `"f4a9a11b-6e71-443d-9289-71a26fe6a018"`'

However, you don't need to use serde_json. You can use Uuid::from_str to achieve what you want. The following runs without issue:

let id = uuid!("f4a9a11b-6e71-443d-9289-71a26fe6a018");
let from_str_id = Uuid::from_str("f4a9a11b-6e71-443d-9289-71a26fe6a018").unwrap();
assert_eq!(from_str_id, id);

Hope this helps!

Thanks for helping out with this @TylerBloom 👍

There hasn't been any activity here for a while so I'll go ahead and close this one, but please feel free to open new issues with anything else you encounter.