Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the json library?

Tags:

json

haskell

I'm trying to figure out Haskell's json library. However, I'm running into a bit of an issue in ghci:

Prelude> import Text.JSON
Prelude Text.JSON> decode "[1,2,3]"

<interactive>:1:0:
    Ambiguous type variable `a' in the constraint:
      `JSON a' arising from a use of `decode' at <interactive>:1:0-15
    Probable fix: add a type signature that fixes these type variable(s)

I think this has something to do with the a in the type signature:

decode :: JSON a => String -> Result a

Can someone show me:

  1. How to decode a string?
  2. What's going with the type system here?
like image 932
Jason Baker Avatar asked Dec 24 '10 00:12

Jason Baker


People also ask

What is JSON library used for?

JSON stands for JavaScript Object Notation. It is a lightweight data exchange format. It is mostly used for transmitting data between servers and client applications.

What are JSON libraries?

library. json is a manifest file of a library package. It allows developers to keep a project in its own structure and define: compatible frameworks and platforms. external dependencies.

What is a JSON file and how do you use it?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

How do I import a JSON file?

IMO simplest way is probably to just put the JSON as a JS object into an ES6 module and export it. That way, you can just import it where you need it. Also, worth noting if you're using Webpack, importing of JSON files will work by default (since webpack >= v2. 0.0 ).


1 Answers

You need to specify which type you want to get back, like this:

decode "[1,2,3]" :: Result [Integer]
-- Ok [1,2,3]

If that line was part of a larger program where you would go on and use the result of decode the type could just be inferred, but since ghci doesn't know which type you need, it can't infer it.

It's the same reason why read "[1,2,3]" doesn't work without a type annotation or more context.

like image 144
sepp2k Avatar answered Nov 15 '22 11:11

sepp2k