Code Monkey home page Code Monkey logo

gjson.rs's Introduction

GJSON
GJSON Playground

get json values quickly

GJSON is a Rust crate that provides a fast and simple way to get values from a json document. It has features such as one line retrieval, dot notation paths, iteration, and parsing json lines.

This library uses the identical path syntax as the Go version.

Getting Started

Usage

Put this in your Cargo.toml:

[dependencies]
gjson = "0.8"

Get a value

Get searches json for the specified path. A path is in dot syntax, such as "name.last" or "age". When the value is found it's returned immediately.

const JSON: &str = r#"{"name":{"first":"Janet","last":"Prichard"},"age":47}"#;

fn main() {
    let value = gjson::get(JSON, "name.last");
    println!("{}", value);
}

This will print:

Prichard

Path Syntax

Below is a quick overview of the path syntax, for more complete information please check out GJSON Syntax.

A path is a series of keys separated by a dot. A key may contain special wildcard characters '*' and '?'. To access an array value use the index as the key. To get the number of elements in an array or to access a child path, use the '#' character. The dot and wildcard characters can be escaped with '\'.

{
  "name": {"first": "Tom", "last": "Anderson"},
  "age":37,
  "children": ["Sara","Alex","Jack"],
  "fav.movie": "Deer Hunter",
  "friends": [
    {"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]},
    {"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]},
    {"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]}
  ]
}
"name.last"          >> "Anderson"
"age"                >> 37
"children"           >> ["Sara","Alex","Jack"]
"children.#"         >> 3
"children.1"         >> "Alex"
"child*.2"           >> "Jack"
"c?ildren.0"         >> "Sara"
"fav\.movie"         >> "Deer Hunter"
"friends.#.first"    >> ["Dale","Roger","Jane"]
"friends.1.last"     >> "Craig"

You can also query an array for the first match by using #(...), or find all matches with #(...)#. Queries support the ==, !=, <, <=, >, >= comparison operators and the simple pattern matching % (like) and !% (not like) operators.

friends.#(last=="Murphy").first    >> "Dale"
friends.#(last=="Murphy")#.first   >> ["Dale","Jane"]
friends.#(age>45)#.last            >> ["Craig","Murphy"]
friends.#(first%"D*").last         >> "Murphy"
friends.#(first!%"D*").last        >> "Craig"
friends.#(nets.#(=="fb"))#.first   >> ["Dale","Roger"]

Value Type

To convert the json value to a Rust type:

value.i8()
value.i16()
value.i32()
value.i64()
value.u8()
value.u16()
value.u32()
value.u64()
value.f32()
value.f64()
value.bool()
value.str()    // a string representation
value.json()   // the raw json

handy functions that work on a value:

value.kind()             // String, Number, True, False, Null, Array, or Object
value.exists()           // returns true if value exists in JSON.
value.get(path: &str)    // get a child value
value.each(|key, value|) // iterate over child values

64-bit integers

The value.i64() and value.u64() calls are capable of reading all 64 bits, allowing for large JSON integers.

value.i64() -> i64   // -9223372036854775808 to 9223372036854775807
value.u64() -> u64   // 0 to 18446744073709551615

Modifiers and path chaining

A modifier is a path component that performs custom processing on the json.

Multiple paths can be "chained" together using the pipe character. This is useful for getting values from a modified query.

For example, using the built-in @reverse modifier on the above json document, we'll get children array and reverse the order:

"children|@reverse"           >> ["Jack","Alex","Sara"]
"children|@reverse|0"         >> "Jack"

There are currently the following built-in modifiers:

  • @reverse: Reverse an array or the members of an object.
  • @ugly: Remove all whitespace from a json document.
  • @pretty: Make the json document more human readable.
  • @this: Returns the current element. It can be used to retrieve the root element.
  • @valid: Ensure the json document is valid.
  • @flatten: Flattens an array.
  • @join: Joins multiple objects into a single object.

Modifier arguments

A modifier may accept an optional argument. The argument can be a valid JSON document or just characters.

For example, the @pretty modifier takes a json object as its argument.

@pretty:{"sortKeys":true} 

Which makes the json pretty and orders all of its keys.

{
  "age":37,
  "children": ["Sara","Alex","Jack"],
  "fav.movie": "Deer Hunter",
  "friends": [
    {"age": 44, "first": "Dale", "last": "Murphy"},
    {"age": 68, "first": "Roger", "last": "Craig"},
    {"age": 47, "first": "Jane", "last": "Murphy"}
  ],
  "name": {"first": "Tom", "last": "Anderson"}
}

The full list of @pretty options are sortKeys, indent, prefix, and width. Please see Pretty Options for more information.

JSON Lines

There's support for JSON Lines using the .. prefix, which treats a multilined document as an array.

For example:

{"name": "Gilbert", "age": 61}
{"name": "Alexa", "age": 34}
{"name": "May", "age": 57}
{"name": "Deloise", "age": 44}
..#                   >> 4
..1                   >> {"name": "Alexa", "age": 34}
..3                   >> {"name": "Deloise", "age": 44}
..#.name              >> ["Gilbert","Alexa","May","Deloise"]
..#(name="May").age   >> 57

Get nested array values

Suppose you want all the last names from the following json:

{
  "programmers": [
    {
      "firstName": "Janet", 
      "lastName": "McLaughlin", 
    }, {
      "firstName": "Elliotte", 
      "lastName": "Hunter", 
    }, {
      "firstName": "Jason", 
      "lastName": "Harold", 
    }
  ]
}

You would use the path "programmers.#.lastName" like such:

value := gjson::get(json, "programmers.#.lastName");
for name in value.array() {
	println!("{}", name);
}

You can also query an object inside an array:

let name = gjson::get(json, "programmers.#(lastName=Hunter).firstName");
println!("{}", name)  // prints "Elliotte"

Iterate through an object or array

The ForEach function allows for quickly iterating through an object or array. The key and value are passed to the iterator function for objects. Only the value is passed for arrays. Returning false from an iterator will stop iteration.

let value := gjson::get(json, "programmers")
value::each(|key, value| {
	println!("{}", value);
	true // keep iterating
});

Simple Parse and Get

There's a gjson::parse(json) function that will do a simple parse, and value.get(path) that will search a value.

For example, all of these will return the same value:

gjson::parse(json).get("name").get("last");
gjson::get(json, "name").get("last");
gjson::get(json, "name.last");

Check for the existence of a value

Sometimes you just want to know if a value exists.

let value = gjson::get(json, "name.last");
if !value.exists() {
	println!("no last name");
} else {
	println!("{}", value);
}

// Or as one step
if gjson::get(json, "name.last").exists() {
	println!("has a last name");
}

Validate JSON

The Get* and Parse* functions expects that the json is valid. Bad json will not panic, but it may return back unexpected values.

If you are consuming JSON from an unpredictable source then you may want to validate prior to using GJSON.

if !gjson::valid(json) {
	return Err("invalid json");
}
let value = gjson::get(json, "name.last");

gjson.rs's People

Contributors

deankarn avatar josteink avatar tidwall 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  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  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  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

gjson.rs's Issues

Iterating first N items in array

The README mentions iterating through the array using ForEach. I'm wondering if there's a way to iterate only through the first N items in the array. Or would that include a counter and an if statement in the ForEach loop? E.g. how would it look like to iterate through the first 5 items in a json document of the form {data: [[2.3, 3.2], [1,2], ... ]]}? Also how would performance compare to streaming parsers e.g. https://github.com/jeremiah-shaulov/nop-json ?

Raw index

Hi @tidwall - thank you for both the Go and Rust version of this library - they're great!

I have a need to modify JSON at a specific path and was going to give it a try using gjson however it does not seem to have an index() func unlike in Golang to determine the byte location for the found value.

Before I dive into the gjson implementation for Rust, maybe you could advise on what you think might be a decent approach to setting arbitrary JSON in Rust? Or maybe it's just a case of a simple update to gjson to expose an index() func?

TIA

plans for adding update functionality?

We recently integrated gjson into nushell via plugin. We were wondering if there were plans on providing the functionality to update based on a query string using gjson. Maybe that already exists and I missed it?

Creating new instances of Value

I'd like to create new instances of each type of value. Specifically, I'm using gjson to read settings from a JSON object, but I need a fucntion that produces a default value for the setting for each accessible key. I'd like to be able to do things like this

let str = Value::String("Foobar");
let num = Value::Number(10);
let ok = Value::Bool(true);
let nothing = Value::Null;

Is this possible?

Literal support?

Hi,

contrary to the Go implementation, this version doesn't seem to implement the literal notation.

const JSON: &str = r#"{"name":{"first":"Janet","last":"Prichard"},"age":47}"#;

fn main() {
    let value = gjson::get(JSON, r#"{name.first,abc:!"abc"}"#);
    println!("{}", value); // Expected {"first":"Janet", "abc": "abc"}
}

Whereas it's

    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/h`
    {"first":"Janet"}

Are there any plans? Or am I doing something wrong?

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.