quda

quda

Function accepting only json as argument, with guard?

Is it possible to create a function to accept only a valid json as parameter/argument ? Not map!
Precisely, I need something that would perform as:

def myFn(obj) when is_json(obj) do
...function content...
end

I am aware that is_json() does not exist in Elixir.
The idea is the function should accept only a string that will parse to json:
myFn("{\"k1\":7,"\k2\":"\hello\"}") should be valid but myFn("bla bla bla") not. (the json objects arrive already stringified from an upstream API)

First Post!

cmo

cmo

Use Jason.decode! to throw or Jason.decode and pattern match on the result. Not in a guard though.

Or similar in whatever json library you’re using.

Most Liked

l00ker

l00ker

I understand your frustration, but I just have to ask the question:

What modern language has native support for JSON?

  • JavaScript has JSON.parse & JSON.stringify to decode & encode JSON via the std library

  • Python has json.loads & json.dumps to decode & encode JSON via import json

  • PHP has json_decode & json_encode to decode & encode JSON via the std library

  • Ruby has JSON.parse & JSON.generate to decode & encode JSON via require 'json'

  • … [1]

The point I’m trying to make is that there doesn’t appear to be a modern language that has – what I would be willing to call – native support for JSON.

Every widely used (modern?) language has functions or methods to encode & decode its native objects or data structures to/from JSON.

Even JavaScript (the ‘J’ in JSON) doesn’t appear to have native support.

JSON (JavaScript Object Notation) is a lightweight data-interchange format [1], and in being such, I believe every language would need to attempt to parse JSON order to determine whether it’s valid or not, and Elixir is no exception. :slight_smile:

  1. json.org
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Guard clauses map to VM level instructions, you can only use those specific clauses in guards, in combinations. The only way to know that a string is JSON is to parse it, and I don’t see how you could create a set of guard clauses that would parse JSON.

hauleth

hauleth

That is not true. Few aren’t constant time:

  • length/1 is linear
  • is_map_key/2 and map access (map_get/2) are logarithmic (and dependants like is_struct/{1,2}

Last Post!

ONeill

ONeill

I dont know if you can do it with a guard but you should be able to do pattern matching in the function clause like

def func(%JSON{} = my_json), do: my_json

That way the function will only match when a JSON struct is passed in.

Edit:

defmodule Test do
  defstruct hello: "world", field: 2
  
  def func(%Test{} = my_struct) do
    IO.puts("Test struct")
  end
end

%Test{hello: "world", field: 2}
|>Test.func()
# Test struct

%{hello: "world", field: 2}
|> Test.func()
# ** (FunctionClauseError) no function clause matching in Test.func/1  

Where Next?

Popular in Questions Top

ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New

Other popular topics Top

stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31586 112
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 40165 209
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 42716 114
New

We're in Beta

About us Mission Statement