Code Monkey home page Code Monkey logo

serde-value's Introduction

arc

excessively sleepy ๐Ÿ’ค

stats

serde-value's People

Contributors

arcnmx avatar arnavion avatar benesch avatar dimbleby avatar natsuki-i avatar sfackler avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

serde-value's Issues

Provide `From` impls

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:

serde-value/src/ser.rs

Lines 77 to 87 in 47190f5

fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
Ok(Value::Bool(v))
}
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
Ok(Value::I8(v))
}
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
Ok(Value::I16(v))
}

this should be trivial to implement.

I can submit a PR if you believe this is worth implementing.

javascript style coerce_to_string or Into<string>

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(",")
        }
    }
}

Changelog

A changelog would be nice, or even just release notes.

Relicense under dual MIT/Apache-2.0

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.

Why?

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.

How?

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!

Contributor checkoff

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.

Enum variants are not distinguishable

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.

release v0.7?

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?

Cannot deserialize into a newtype tuple struct

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");

Value<'de>

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.

Move into Serde

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.)

MapVisitor's missing_field doesn't handle Option properly

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.

Consider providing distinct value types for ser and de

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.

Traversing a nested 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?

maps with duplicates

would be very nice to have support for maps with duplicates. possibly behind a flag or something.

Provide separate ValueDeserializer that's generic on the Error type

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.