Serde json key must be a string

I want to create a struct from a JSON string that looks like this:

{modules: []} // the JSON string

struct UserData {
     modules: Vec<Modules>
}

And I use the following code to parse it into the given struct:

let user_data: UserData = serde_json::from_str(&json_str).unwrap();

But this gives me an error: Error("key must be a string", line: 1, column: 2)
Does this happen because the string does not look like this? {"modules": []} How can I fix this?

This is not JSON. In JSON every object key is always a string.

If you want to support this, you will need to find some format that supports this and a serde deserializer for it (or write one yourself).

1 Like

So I have to use serde_json::to_string() first?

No. That still won't work.

Can you give me an example for a serde serializer?

Sorry, I mean deserializer (something to replace your from_str()).

Can you give me an example for this?

Your data is not valid JSON, but it is valid JSON5 so you should be able to use the json5 crate for this.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.