arc
excessively sleepy
Serialization value trees
Home Page: http://arcnmx.github.io/serde-value/serde_value/
License: MIT License
I'd like to use this crate's serde_value::Value
as a more generic version of serde_json::Value
.
My use case is an HTTP API where the success response body is defined as such:
#[derive(serde::Serialize)]
struct SuccessBody {
data: serde_json::Value,
}
impl SuccessBody {
pub fn new(data: impl Into<serde_json::Value>) -> Self {
let data = data.into();
Self { data }
}
}
Since most (all?) serialize_*
are infallible, e.g:
Lines 77 to 87 in 47190f5
I can submit a PR if you believe this is worth implementing.
fn coerce_to_string(value: serde_value::Value) -> String {
match value {
serde_value::Value::Bool(v) => v.to_string(),
serde_value::Value::U8(v) => v.to_string(),
serde_value::Value::U16(v) => v.to_string(),
serde_value::Value::U32(v) => v.to_string(),
serde_value::Value::U64(v) => v.to_string(),
serde_value::Value::I8(v) => v.to_string(),
serde_value::Value::I16(v) => v.to_string(),
serde_value::Value::I32(v) => v.to_string(),
serde_value::Value::I64(v) => v.to_string(),
serde_value::Value::F32(v) => v.to_string(),
serde_value::Value::F64(v) => v.to_string(),
serde_value::Value::Char(v) => v.to_string(),
serde_value::Value::String(v) => v,
serde_value::Value::Unit => "".to_string(),
serde_value::Value::Option(v) => match v {
Some(v) => coerce_to_string(*v),
None => "null".to_string(),
},
serde_value::Value::Newtype(v) => coerce_to_string(*v),
serde_value::Value::Seq(v) => {
let l: Vec<_> = v.into_iter().map(coerce_to_string).collect();
l.join(",")
}
serde_value::Value::Map(_) => "[object Object]".to_string(),
serde_value::Value::Bytes(v) => {
let l: Vec<_> = v.into_iter().map(|v| v.to_string()).collect();
l.join(",")
}
}
}
A changelog would be nice, or even just release notes.
This issue was automatically generated. Feel free to close without ceremony if
you do not agree with re-licensing or if it is not possible for other reasons.
Respond to @cmr with any questions or concerns, or pop over to
#rust-offtopic
on IRC to discuss.
You're receiving this because someone (perhaps the project maintainer)
published a crates.io package with the license as "MIT" xor "Apache-2.0" and
the repository field pointing here.
TL;DR the Rust ecosystem is largely Apache-2.0. Being available under that
license is good for interoperation. The MIT license as an add-on can be nice
for GPLv2 projects to use your code.
The MIT license requires reproducing countless copies of the same copyright
header with different names in the copyright field, for every MIT library in
use. The Apache license does not have this drawback. However, this is not the
primary motivation for me creating these issues. The Apache license also has
protections from patent trolls and an explicit contribution licensing clause.
However, the Apache license is incompatible with GPLv2. This is why Rust is
dual-licensed as MIT/Apache (the "primary" license being Apache, MIT only for
GPLv2 compat), and doing so would be wise for this project. This also makes
this crate suitable for inclusion and unrestricted sharing in the Rust
standard distribution and other projects using dual MIT/Apache, such as my
personal ulterior motive, the Robigalia project.
Some ask, "Does this really apply to binary redistributions? Does MIT really
require reproducing the whole thing?" I'm not a lawyer, and I can't give legal
advice, but some Google Android apps include open source attributions using
this interpretation. Others also agree with
it.
But, again, the copyright notice redistribution is not the primary motivation
for the dual-licensing. It's stronger protections to licensees and better
interoperation with the wider Rust ecosystem.
To do this, get explicit approval from each contributor of copyrightable work
(as not all contributions qualify for copyright, due to not being a "creative
work", e.g. a typo fix) and then add the following to your README:
## License
Licensed under either of
* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
additional terms or conditions.
and in your license headers, if you have them, use the following boilerplate
(based on that used in Rust):
// Copyright 2016 serde-value developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
It's commonly asked whether license headers are required. I'm not comfortable
making an official recommendation either way, but the Apache license
recommends it in their appendix on how to use the license.
Be sure to add the relevant LICENSE-{MIT,APACHE}
files. You can copy these
from the Rust repo for a plain-text
version.
And don't forget to update the license
metadata in your Cargo.toml
to:
license = "MIT/Apache-2.0"
I'll be going through projects which agree to be relicensed and have approval
by the necessary contributors and doing this changes, so feel free to leave
the heavy lifting to me!
To agree to relicensing, comment with :
I license past and future contributions under the dual MIT/Apache-2.0 license, allowing licensees to chose either at their option.
Or, if you're a contributor, you can check the box in this repo next to your
name. My scripts will pick this exact phrase up and check your checkbox, but
I'll come through and manually review this issue later as well.
If I understand serde
correctly, the serialize_<...>_variant
functions should emit an externally tagged enum, i.e. some sort of map "variant" => <content>
(or simply "variant"
in case of a unit-variant). Currently the serializer does not store any information on the enum variant (e.g. in serialize_unit_variant
), which effectively transforms this into an untagged enum. Thus multiple variants (e.g. of unit-type) are not distinguishable.
Thanks for the recent merges, @arcnmx! I saw you bumped the version in the Cargo.toml to 0.7, but doesn't look like you published to crates.io. If that was intentional, do you have a sense of when you plan to cut 0.7?
The following code works OK:
use serde::{Deserialize, Serialize};
use serde_json;
use serde_value;
use uuid;
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]
struct EventId(uuid::Uuid);
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]
struct Event<I> {
id: I,
}
#[test]
fn newtype_deserialization() {
let ev = Event {
id: EventId(uuid::Uuid::nil()),
};
let serialized = serde_json::to_string(&ev).expect("Serialization error");
assert_eq!(
serialized,
r#"{"id":"00000000-0000-0000-0000-000000000000"}"#
);
//let value: serde_value::Value =
let value: serde_json::Value =
serde_json::from_str(&serialized).expect("Deserialization error");
let deserialized: Event<EventId> =
Event::deserialize(value.clone()).expect("Deserialization error");
assert_eq!(deserialized, ev);
}
However, if I try to use:
- //let value: serde_value::Value =
- let value: serde_json::Value =
+ let value: serde_value::Value =
+ //let value: serde_json::Value =
serde_json::from_str(&serialized).expect("Deserialization error");
I receive the following error:
thread 'newtype_deserialization' panicked at 'Deserialization error: InvalidType(Str("00000000-0000-0000-0000-000000000000"), "tuple struct EventId")', src/libcore/result.rs:997:5
which makes troubles to use serde_value::Value
as intermediate representation in deserialization scenarios.
Also, .clone()
here is required by serde_value::Value
, while serde_json::Value
can just borrow (I believe this is the same as #15):
let deserialized: Event<EventId> =
Event::deserialize(value.clone()).expect("Deserialization error");
It would be useful to have variants in Value to hold &'de str
and &'de [u8]
. This enables support for borrowed data in code like the following.
let v: Value = Deserialize::deserialize(deserializer)?;
{
/* some logic, inspecting or mutating the Value */
}
return T::deserialize(v);
Currently in such a case T cannot borrow from the original Deserializer. This came up in serde-rs/serde#1028.
When serde-value is stable and polished and considering a 1.0 release, let's re-evaluate whether it makes sense to provide this functionality directly in Serde.
(This was previously tracked in serde-rs/serde#741.)
A nicer form of the forward_to_deserialize!
macro from this crate is now built into serde:
https://docs.serde.rs/serde/macro.forward_to_deserialize.html
serde_json has been supporting it for a while (via indexmap), would it possible here as well?
MapVisitor's missing_field implementation currently delegates to deserializing from a Value::Unit
, but this unfortunately doesn't work for the use case of having an Optional<Foo>
field that will be set to None
if the field isn't provided, since Optional
's Visitor
only handles visit_some
and visit_none
.
missing_field's default implementation gets around this by using a ValueDeserializer
for ()
, which pays attention to the visit_option
hint: https://github.com/serde-rs/serde/blob/master/serde/src/de/value.rs#L109-L119.
serde_json does something similar but with a local Deserializer: https://serde-rs.github.io/json/src/serde_json/value.rs.html#951 for some reason.
Internally, Serde operations that require buffering a value use two different types for ser
and de
. Among the differences are ser
distinguishes between seq and tuple while de
does not, de
has a lifetime parameter to hold &'de str
while ser
does not.
This may make sense to mirror here depending on the intended use cases of serde-value.
Hello,
I use Value to get JSON structs from protobuf: https://github.com/sevagh/pq/blob/master/src/decode.rs#L45
I need to go into this structure, find any map with a String key, and modify that key. Here's an example of serde::Value
that I need to work with:
Map(
{
String(
"my_child"
): Option(
Some(
Map(
{
String(
"foo_bar"
): Option(
Some(
String(
"baz"
)
)
)
}
)
)
)
}
)
Here I need to get the strings "my_child"
and "foo_bar"
.
I'm kinda stuck writing a match statement that can recursively find all the Map(String, _)
s in this object. Any suggestions?
would be very nice to have support for maps with duplicates. possibly behind a flag or something.
The serde::private::de::Content
does not impl Deserializer
itself, rather a separate ContentDeserializer
type implements it. This allows ContentDeserializer
to be used inside Deserialize
impls, since Deserialize
impls must be generic on the Error
type.
The same cannot be done with serde_value::Value
since it impls Deserializer
on itself with a fixed Error = serde_value::DeserializerError
type.
It would be useful to have a separate
struct ValueDeserializer<E: serde::de::Error>(Value, PhantomData<E>);
impl<'de, E: serde::de::Error> Deserialize<'de> for ValueDeserializer<E> {
type Error = E;
// same as current Value impl, except for visit_seq and visit_map
// that need to wrap the value in Self first
}
Content
's Deserializer
impl could then forward to ContentDeserializer<serde_value::DeserializerError>
to maintain backward compatibility.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.