Code Monkey home page Code Monkey logo

json's Introduction

json ๐Ÿ‘

Work with JSON in Gleam!

Under the hood library uses Thoas, the fastest and most memory efficient pure Erlang JSON encoder/decoder.

Installation

Add this package to your Gleam project.

gleam add gleam_json

Encoding

import myapp.{Cat}
import gleam/json.{object, string, array, int, null}

pub fn cat_to_json(cat: Cat) -> String {
  object([
    #("name", string(cat.name)),
    #("lives", int(cat.lives)),
    #("flaws", null()),
    #("nicknames", array(cat.nicknames, of: string)),
  ])
  |> json.to_string
}

Decoding

JSON is decoded into a Dynamic value which can be decoded using the gleam/dynamic module from the Gleam standard library.

import myapp.{Cat}
import gleam/json
import gleam/dynamic.{field, list, int, string}

pub fn cat_from_json(json_string: String) -> Result(Cat, json.DecodeError) {
  let cat_decoder = dynamic.decode3(
    Cat,
    field("name", of: string),
    field("lives", of: int),
    field("nicknames", of: list(string)),
  )

  json.decode(from: json_string, using: cat_decoder)
}

json's People

Contributors

akiomik avatar chazsconi avatar crowdhailer avatar j3rn avatar janiczek avatar lpil avatar lunarmagpie avatar michallepicki avatar mrkutly avatar pgbiel avatar wowi42 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

Watchers

 avatar  avatar  avatar  avatar  avatar

json's Issues

Array of Json

I'm trying to get an array of json objects that are already into json objects. I think I could state they are Json but it's not letting me get access to the Json type in this library.

let objects = [json.object([#("test", json.string("one"))])]
json.array(objects, json.Json)
error: Unknown module field
   โ”Œโ”€ /home/rockerboo/code/image_scorer/test/gleam_json_test.gleam:12:27
   โ”‚
12 โ”‚   json.array(objects, json.Json)
   โ”‚                           ^^^^^ Did you mean `bool`?

The module `gleam/json` does not have a `Json` value.
import gleam/json
import gleeunit
import gleeunit/should

pub fn main() {
  gleeunit.main()
}

pub fn json_test() {
  let objects = [json.object([#("test", json.string("one"))])]

  json.array(objects, json.Json)
}

What is the expected behavior to accomplish this? Thank you!

JSON into BitArray fails to decode

I am trying to take the JSON representation and turn it into a BitArray. Now I may be doing this incorrectly but I can't find another documented way to translate it over. Ideally it would be nice for the gleam_json library supports converting it directly to BitArray but I can work with how it is.

I took the encode test to show that it encodes properly but converting it to base64 returns a error (nil). Hard to tell what happens.

import gleam/bit_array

pub fn encode_object_2_test() {
  json.object([
    #("messageType", json.string("getRating")),
    #("error", json.string("invalid rating")),
  ])
  |> should_encode(
    "{\"messageType\":\"getRating\",\"error\":\"invalid rating\"}",
  )

  json.object([
    #("messageType", json.string("getRating")),
    #("error", json.string("invalid rating")),
  ])
  |> json.to_string()
  |> bit_array.base64_decode()
  |> should.be_ok()
}
  1) gleam_json_test.encode_object_2_test
     Failure: ?assertMatch({ ok , _ }, A)
       expected: = { ok , _ }
            got: {error,nil}
     output:

Thank you!

Pretty print with newlines and indentation

Currently json.to_string() gives a string with no whitespace. This is sufficient much of the time, but it's also useful to be able to pretty print with newlines and indentations so it's more human-readable.

E.g.

> to_pretty_string(array([1, 2, 3], of: int))
"[\n  1,\n  2,\n  3\n]"

> to_pretty_string(object([#("foo", string("bar")]))
"{\n  \"foo\": \"bar\"\n}"

Add support to decode tuple

Thank you for the great language and libraries.

I would like to decode the following JSON:

["1234", {"id": "5678", "created_at": 123}]

So I tried the following code, but an error occurred.

import gleam/dynamic.{field, element}
import gleam/json.{decode}

pub type InnerData {
  InnerData(id: String, created_at: Int)
}

pub type OuterData {
  OuterData(label: String, data: InnerData)
}

let inner_data_decoder = dynamic.decode2(
  InnerData,
  field("id", dynamic.string),
  field("created_at", dynamic.int),
)

let outer_data_decoder = dynamic.decode2(
  OuterData,
  element(0, dynamic.string),
  element(1, inner_data_decoder),
)

decode("[\"1234\", {\"id\": \"5678\", \"created_at\": 123}]", outer_data_decoder)

// {error,
//   {unexpected_format,
//    [{decode_error,<<"Tuple">>,<<"List">>,[]},
//     {decode_error,<<"Tuple">>,<<"List">>,[]}]}}

This error indicates that the root JSON type is automatically treated as a list. This can be avoided by using json.decode and dynamic.any, but it is not smart.

It would be great if you could support tuples to make it easier to dacode to any custom type.

Supporting floats from json represented like integers

const x = {float: 1.0}
// x = {float: 1}
JSON.stringify(x)
// {"float": 1}
import gleam/dynamic.{dict, float, string}
import gleam/json

pub fn json_float_test() {
  let json_string = "{\"float\": 1}"

  let assert Ok(_) = json.decode(json_string, dict(string, float))
}
  1) json_test.json_float_test: module 'json_test'
     #{function => <<"json_float_test">>,line => 7,
       message => <<"Assertion pattern match failed">>,
       module => <<"json_test">>,
       value =>
           {error,
               {unexpected_format,
                   [{decode_error,<<"Float">>,<<"Int">>,[<<"values">>]}]}},
       gleam_error => let_assert}
     location: json_test.json_float_test:7
     stacktrace:
       json_test.json_float_test
     output:

And what would work if I made it manually and not use JSON.stringify

pub fn json_float_manually_test() {
  let json_string = "{\"float\": 1.0}"

  let assert Ok(_) = json.decode(json_string, dict(string, float))
}

Right now I am having to convert the float by adding 0.00000001 or some small value to it to force it to make it a float representation. Would it be possible to allow the 1 be able to be a float on the gleam side? Possibly there is some way to convert the int to a float in the process? Just that I want to pass it always as a float but the json string representation will convert it to an int if it's like 1.0.

Thank you.

can not decode to dict(string, dynamic)

pub fn main() {
 let json = "
{
  \"args\": {},
  \"data\": \"{}\",
  \"files\": {},
  \"form\": {},
  \"headers\": {
    \"Accept\": \"application/json\",
    \"Content-Length\": \"2\",
    \"Content-Type\": \"application/json\",
    \"Host\": \"httpbin.org\",
    \"User-Agent\": \"hackney/1.20.1\",
    \"X-Amzn-Trace-Id\": \"Root=1-65f91087-2514879b1bbf428c25655ebd\"
  },
  \"json\": {},
  \"origin\": \"116.4.240.112\",
  \"url\": \"https://httpbin.org/post\"
}
"

    let result = json|>
    json.decode(dynamic.dict(dynamic.string, dynamic.dynamic))
    |> result.unwrap(or: dict.new())
    |> dict.get("json")
    |> result.unwrap(or: dynamic.from("NOT FOUND"))
    |> dynamic.string
    |> result.unwrap(or: "NOT FOUND")
    
    io.println("result: " <> result)
}
โ”€โฏ gleam run 
  Compiling hello
   Compiled in 0.29s
    Running hello.main
result: NOT FOUND
  • gleam_json = "~> 1.0"
  • gleam = 1.0.0

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.