#json #literals #string-literal #write #ugly

dev json_str

Write json literals without ugly strings

14 releases

Uses old Rust 2015

0.5.2 Apr 29, 2018
0.5.1 Dec 18, 2017
0.5.0 Jan 15, 2017
0.3.4 Nov 25, 2016
0.3.1 Jul 4, 2016

#59 in #string-literal

Download history 3/week @ 2023-12-14 15/week @ 2023-12-21 18/week @ 2023-12-28 29/week @ 2024-01-04 16/week @ 2024-01-11 48/week @ 2024-01-18 56/week @ 2024-01-25 56/week @ 2024-02-01 81/week @ 2024-02-08 75/week @ 2024-02-15 41/week @ 2024-02-22 42/week @ 2024-02-29 34/week @ 2024-03-07 24/week @ 2024-03-14 33/week @ 2024-03-21 28/week @ 2024-03-28

120 downloads per month
Used in 4 crates

Apache-2.0

15KB
217 lines

json_str

Build Status Latest Version

Docs and samples

Use json_str for standardised json literals:

let json = json_str!({
    query: {
        query_string: {
            query: "*"
    }
});

Use json_fn for standardised json that supports variable substitutions:

let get_json = json_fn!(|qry| {
    query: {
        query_string: {
            query: $qry
    }
});

let json = get_json("\"some value\"");

Also see the json macro from serde_json. If you're building complex or dynamic structures, especially on stable, it'll be a better approach.

Details

This crate is an ergonomic way to build json strings in Rust on the stable and nightly channels. Rust has a json-like syntax for defining structures, so it's easy to convert some valid Rust token trees into json. This crate will also minify whitespace and standardise quotes while it's building the String.

On stable, conversion is provided by a simple macro. On nightly, conversion is provided by a compiler plugin that sanitises the input at compile time instead of runtime. The nightly channel also provides an alternative plugin for creating &str literals instead of a String, to avoid that allocation.

Don't trust user input!

json_fn is not intended to be used with raw user-input. Values are spliced in as-is, with no sanitisation or escaping done. The parsing (which is also not designed to be secure, it expects trusted input since it come directly from the app binary) runs before any values are substituted. Make sure you verify your inputs appropriately!

No runtime deps

Features