Project

json-pie

0.0
No release in over a year
Easily parse JSON:API data structures into ActiveRecord resources. This will parse deeply nested relationships as well as attributes.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Runtime

<= 7.1
 Project Readme

JSON::Pie

Parse JSON:API data structures into Rails ActiveRecord structures.

Tests Linting

Installation

gem "json-pie"

Usage

Your models:

class User < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :user
end

In your controller:

class ArticleController
  def create
    article = JSON::Pie.parse params
    article.save!
    render json: article, status: :created
  end
end

Then send this JSON structure to your application will create a new article with #<User @id=1 ...> as the author.

{
  "data": {
    "type": "article",
    "attributes": {
      "title": "New article"
    },
    "relationships": {
      "user": {
        "data": {
          "type": "user",
          "id": 1
        }
      }
    }
  }
}

Decoupling from your models

It's fairly easy to decouple the publis JSON:API that you parse from the actual data structure beneath by using the options.

JSON::Pie.parse(params, **options)
option description
type_map A hash that maps JSON:API types to the actual models in your system. E.g. { author: :user }