Skip to content

Commit

Permalink
WIP: Add methods for querying JSON values
Browse files Browse the repository at this point in the history
TODO: write description here.

This fixes #356.

Changelog: added
  • Loading branch information
yorickpeterse committed Dec 16, 2023
1 parent e287956 commit a0861b1
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions std/src/std/json.inko
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,63 @@ impl ToString for Error {
}
}

class pub Query {
let @value: Option[ref Json]

fn pub move key(name: String) -> Query {
@value = match ref @value {
case Some(Object(v)) -> v.opt(name)
case _ -> Option.None
}

self
}

fn pub move index(index: Int) -> Query {
@value = match ref @value {
case Some(Array(v)) -> v.opt(index)
case _ -> Option.None
}

self
}

fn pub string -> Option[String] {
match @value {
case Some(String(v)) -> Option.Some(v)
case _ -> Option.None
}
}

fn pub int -> Option[Int] {
match @value {
case Some(Int(v)) -> Option.Some(v)
case _ -> Option.None
}
}

fn pub float -> Option[Float] {
match @value {
case Some(Float(v)) -> Option.Some(v)
case _ -> Option.None
}
}

fn pub object -> Option[ref Map[String, Json]] {
match @value {
case Some(Object(v)) -> Option.Some(v)
case _ -> Option.None
}
}

fn pub array -> Option[ref Array[Json]] {
match @value {
case Some(Array(v)) -> Option.Some(v)
case _ -> Option.None
}
}
}

# A JSON value, such as `true` or an array.
class pub enum Json {
case Int(Int)
Expand Down Expand Up @@ -237,6 +294,18 @@ class pub enum Json {
fn pub to_pretty_string -> String {
Generator.new(DEFAULT_PRETTY_INDENT).generate(self)
}

fn pub query -> Query {
Query { @value = Option.Some(self) }
}

fn pub key(name: String) -> Query {
query.key(name)
}

fn pub index(index: Int) -> Query {
query.index(index)
}
}

impl ToString for Json {
Expand Down

0 comments on commit a0861b1

Please sign in to comment.