|
1 | 1 | # serde-value |
2 | 2 |
|
3 | | -`serde-cw-value` provides a way to capture serialization value trees for later processing. Crate is designed to work with CosmWasm smart contracts, |
4 | | -in particular - it errors early when any floating-point types are processed. This is for of [serde-value](https://github.com/arcnmx/serde-value). |
| 3 | +`serde-cw-value` provides a way to capture serialization value trees for later |
| 4 | +processing. Crate is designed to work with CosmWasm smart contracts, in |
| 5 | +particular - it errors early when any floating-point types are processed. This |
| 6 | +is for of [serde-value](https://github.com/arcnmx/serde-value). |
5 | 7 |
|
| 8 | +# Usage |
6 | 9 |
|
| 10 | +Add the library to the project with `cargo add`: |
| 11 | + |
| 12 | +``` |
| 13 | +cargo add serde-cw-value |
| 14 | +``` |
| 15 | + |
| 16 | +Then you can deserialize any serde source to intermediate |
| 17 | +`serde_cw_value::Value` representing any structure deserializable by serde. For |
| 18 | +example you can deserialize arbitrary Json without knowing it's exact |
| 19 | +structure: |
| 20 | + |
| 21 | +```rust |
| 22 | +const json: &str = r#"{ "field": "value" }"#; |
| 23 | + |
| 24 | +fn main() { |
| 25 | + let value = serde_json_wasm::from_str(json).unwrap(); |
| 26 | + |
| 27 | + let Value::Map(m) = value else { unreachable!() }; |
| 28 | + let v = m.get(&Value::String("field".to_owned())).unwrap(); |
| 29 | +} |
| 30 | +``` |
| 31 | + |
| 32 | +This might be usefull for example when smart contract is forwarding a Json |
| 33 | +received in the message, but not knowing it full structure. This will verify |
| 34 | +that underlying data is a proper JSON, and also it allow you to figure out its |
| 35 | +structure. |
| 36 | + |
| 37 | +It is also possible to deserialize the `Value` further to a proper structure: |
| 38 | + |
| 39 | +```rust |
| 40 | +const json: &str = r#"{ "field": "value" }"#; |
| 41 | + |
| 42 | +#[derive(Deserialize)] |
| 43 | +struct Data { |
| 44 | + field: String, |
| 45 | +} |
| 46 | + |
| 47 | +fn main() { |
| 48 | + let value = serde_json_wasm::from_str(json).unwrap(); |
| 49 | + let data: Data = value.deserialize_into(); |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +It is always better to deserialize directly to final structure if possible, but |
| 54 | +there are some cases, when deserialization has to be delayed. Also the `Value` |
| 55 | +type is implementing `Clone` so it is possible to deserialize data to `Value`, |
| 56 | +and then deserialize it to final type keeping the intermediate reprezentation |
| 57 | +for future. |
| 58 | + |
| 59 | +Finally, as `Value` also implements `Serialize` it is possible to transcribe one |
| 60 | +format to another using this, without any knowledge of the internal data, by |
| 61 | +first deserializing original format to `Value`, and then serializing it back |
| 62 | +to the new format. |
0 commit comments