使用JSON API Serializer创建更复杂的JSON

gz5pxeao  于 2023-07-01  发布在  其他
关注(0)|答案(2)|浏览(75)

例子here在解释如何产生更复杂的结构方面还远远不够。
如果我想以这样的方式结束:

{
  "data": {
    "type": "mobile_screens",
    "id": "1",
    "attributes": {
      "title": "Watch"
    },
    "relationships": {
      "mobile_screen_components": {
        "data": [
          {
            "id": "1_1",
            "type": "mobile_screen_components"
          },
          {
            "id": "1_2",
            "type": "mobile_screen_components"
          },
          ...
        ]
      }
    }
  },
  "included": [
    {
      "id": "1_1",
      "type": "mobile_screen_components",
      "attributes": {
        "title": "Featured Playlist",
        "display_type": "shelf"
      },
      "relationships": {
        "playlist": {
          "data": {
            "id": "938973798001",
            "type": "playlists"
          }
        }
      }
    },
    {
      "id": "938973798001",
      "type": "playlists",
      "relationships": {
        "videos": {
          "data": [
            {
              "id": "5536725488001",
              "type": "videos"
            },
            {
              "id": "5535943875001",
              "type": "videos"
            }
          ]
        }
      }
    },
    {
      "id": "5536725488001",
      "type": "videos",
      "attributes": {
        "duration": 78321,
        "live_stream": false,
        "thumbnail": {
          "width": 1280,
          "url":
            "http://xxx.jpg?pubId=694940094001",
          "height": 720
        },
        "last_published_date": "2017-08-09T18:26:04.899Z",
        "streams": [
          {
            "url":
              "http://xxx.m3u8",
            "mime_type": "MP4"
          }
        ],
        "last_modified_date": "2017-08-09T18:26:27.621Z",
        "description": "xxx",
        "fn__media_tags": [
          "weather",
          "personality"
        ],
        "created_date": "2017-08-09T18:23:16.830Z",
        "title": "NOAA predicts most active hurricane season since 2010",
        "fn__tve_authentication_required": false
      }
    },
    ...,
  ]
}

我能设置的最简单的数据结构和序列化程序是什么?
我被这样的事情难倒了:

const mobile_screen_components = responses.map((currentValue, index) => {
  id[`id_${index}`];
});
const dataSet = {
  id: 1,
  title: 'Watch',
  mobile_screen_components,
};
const ScreenSerializer = new JSONAPISerializer('mobile_screens', {
  attributes: ['title', 'mobile_screen_components'],
  mobile_screen_components: {
    ref: 'id',
  }
});

这只给了我:

{
  "data": {
    "type": "mobile_screens",
    "id": "1",
    "attributes": { "title": "Watch" },
    "relationships": {
      "mobile-screen-components": {
        "data": [
          { "type": "mobile_screen_components", "id": "1_0" },
          { "type": "mobile_screen_components", "id": "1_1" },
          { "type": "mobile_screen_components", "id": "1_2" },
          { "type": "mobile_screen_components", "id": "1_3" },
          { "type": "mobile_screen_components", "id": "1_4" },
          { "type": "mobile_screen_components", "id": "1_5" }
        ]
      }
    }
  }
}

我不知道如何让“included”兄弟节点到“data”等等。

i1icjdpr

i1icjdpr1#

所以问题是
我能设置的最简单的数据结构和序列化程序是什么?
下面是可以使用jsonapi-serializer转换为JSON的最简单对象,类似于问题中的JSON:

let dataSet = {
  id: '1',
  title: 'Watch',
  mobile_screen_components: [
    {
      id: '1_1',
      title: 'Featured Playlists',
      display_type: 'shelf',
      playlists: {
        id: 938973798001,
        videos: [
          {
            id: 5536725488001,
            duration: 78321,
            live_stream: false
          },
          {
            id: 5535943875001,
            duration: 52621,
            live_stream: true
          }
        ]
      }
    }
  ]
};

为了将此对象序列化为JSON API,我使用了以下代码:

let json = new JSONAPISerializer('mobile_screen', {
  attributes: ['id', 'title', 'mobile_screen_components'],
  mobile_screen_components: {
    ref: 'id',
    attributes: ['id', 'title', 'display_type', 'playlists'],
    playlists: {
      ref: 'id',
      attributes: ['id', 'videos'],
      videos: {
        ref: 'id',
        attributes: ['id', 'duration', 'live_stream']
      }
    }
  }
}).serialize(dataSet);

console.log(JSON.stringify(json, null, 2));
  1. JSONAPISerializer构造函数的第一个参数是资源类型。
    1.第二个参数是序列化选项。
    1.选项的每个级别都等于序列化对象中嵌套对象的级别。
  2. ref-如果存在,则被视为关系。
  3. attributes-要显示的属性数组。
gk7wooem

gk7wooem2#

简介

首先我们要了解JSON APIdocument data structure

**[0.1]**引用顶层(对象根键):

文档必须至少包含以下顶级成员之一:

data: the document’s “primary data” 
errors: an array of error objects   
meta: a meta object that contains non-standard meta-information.

文档MAY包含以下任何顶级成员:

jsonapi: an object describing the server’s implementation
links: a links object related to the primary data.
included: an array of resource objects that are related to the primary data and/or each other (“included resources”).

**[0.2]

文档的“主数据”是请求所针对的资源或资源集合的表示。
主数据必须为:
1.单个资源标识符对象或null,用于以单个资源为目标的请求
1.资源标识符对象的数组,或用于请求的空数组([])。以收藏为目标

示例

以下主数据是单个资源对象:

{
  "data": {
    "type": "articles",
    "id": "1",
    "attributes": {
      // ... this article's attributes
    },
    "relationships": {
      // ... this article's relationships
    }
  }
}

在(jsonapi-serializer)文档中:可用的序列化选项(opts参数)
因此,为了添加included(* 顶级成员 *),我执行了以下测试:

var JsonApiSerializer = require('jsonapi-serializer').Serializer;
const DATASET = {
  id:23,title:'Lifestyle',slug:'lifestyle',
  subcategories: [
   {description:'Practices for becoming 31337.',id:1337,title:'Elite'},
   {description:'Practices for health.',id:69,title:'Vitality'}
  ]
}
const TEMPLATE = {
  topLevelLinks:{self:'http://example.com'},
  dataLinks:{self:function(collection){return 'http://example.com/'+collection.id}},
  attributes:['title','slug','subcategories'],
  subcategories:{ref:'id',attributes:['id','title','description']}
}
let SERIALIZER = new JsonApiSerializer('pratices', DATASET, TEMPLATE)
console.log(SERIALIZER)

输出如下:

{ links: { self: 'http://example.com' },
  included: 
   [ { type: 'subcategories', id: '1337', attributes: [Object] },
     { type: 'subcategories', id: '69', attributes: [Object] } ],
  data: 
   { type: 'pratices',
     id: '23',
     links: { self: 'http://example.com/23' },
     attributes: { title: 'Lifestyle', slug: 'lifestyle' },
     relationships: { subcategories: [Object] } } }

正如您所看到的,included已正确填充。

注意:如果您需要有关dataSet的更多帮助,请使用原始数据编辑您的问题。

相关问题