Json in PureScript
Our first program will demonstrate how to work with JSON data in PureScript. Here’s the full source code:
This program demonstrates how to work with JSON in PureScript:
We import necessary modules for JSON encoding/decoding and other utilities.
We define custom data types
Response1
andResponse2
, similar to structs in other languages.We implement
EncodeJson
andDecodeJson
instances forResponse2
to allow custom JSON encoding and decoding.In the
main
function, we demonstrate:- Encoding basic data types, arrays, and objects to JSON.
- Encoding custom data types to JSON.
- Decoding JSON strings into PureScript data structures.
- Decoding JSON into custom data types.
- Encoding JSON directly to console output.
We use
stringify
to convert JSON values to strings for output.For decoding, we use pattern matching with
case
expressions to handle potential errors and extract values.We demonstrate how to access nested data in decoded JSON objects.
To run this program, you would typically compile it with the PureScript compiler and then run it with Node.js. The exact commands may vary depending on your project setup, but it might look something like this:
This example covers the basics of JSON handling in PureScript. For more advanced usage, you may want to refer to the documentation of the purescript-argonaut-core
and purescript-argonaut-codecs
libraries.