gleam-lang / json Goto Github PK
View Code? Open in Web Editor NEW๐ Work with JSON in Gleam!
Home Page: https://hexdocs.pm/gleam_json/
License: Apache License 2.0
๐ Work with JSON in Gleam!
Home Page: https://hexdocs.pm/gleam_json/
License: Apache License 2.0
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.
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!
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}"
Hello, is exists best practice for encoding/decoding of Dict
, Result
?
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!
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
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.