2

I'm writing a library to deserialize a subset of JSON into predefined Python types.

I want to deserialize arbitrary JSON into an object that quacks like serde-json's Value. However, I don't want it to deserialize into String's, Number's and Bool's - instead when the deserializer hits one of these I would prefer it simply keeps a reference to the respective byte string so I can efficiently (i.e. without the additional type conversion) parse the byte strings into the correct arbitrary Python types. Something like this:

use serde::Deserialize;
use serde_json::value::RawValue;
use serde_json::Map;

#[derive(Deserialize)]
pub enum MyValue<'a> {
    Null,
    Bytes(&'a RawValue),
    Array(Vec<MyValue<'a>>),
    Object(Map<String, MyValue<'a>>),
}

This will require writing a lot of traits so that it behaves like Value, and I'm not even sure if it won't just ignore deserializing the structural parts and put everything into a RawValue.

What is the cleanest way to do this?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
wnorcbrown
  • 53
  • 4
  • Json is a text-based protocol even if you store binary as json string in base64 encoding it would cost you twice the storage and network bandwidth. I think you should have a look at bincode – nikoss Dec 21 '21 at 14:40
  • @nikoss I just want to keep a reference to a slice of a JSON byte-string that is already in memory. There shouldn't be any copying as far as I am aware. Thanks, I'll check out bincode. – wnorcbrown Dec 21 '21 at 14:45
  • 1
    "This will require writing a lot of traits" I'm not sure that's true, you can probably implement `Deserialize` for `MyValue` (by hand, no deriving), try the 3 specific cases, then fallback on desertialising a RawValue (which should always work). – Masklinn Dec 21 '21 at 14:51
  • What do you mean by already in memory? if it's there already why do you need to parse it I think your question needs more clarification. Are you trying to intercept the memory of another process? – nikoss Dec 21 '21 at 14:56
  • @Masklinn Thanks, I had considered this, but I was wary because I also want the interface that `Value` provides e.g. the indexing. Maybe this is the only way though. – wnorcbrown Dec 21 '21 at 15:00

0 Answers0