如何将第二个项添加到JSON数组中,仅当有一个项时?

时间 2019-02-21
阅读 25
点赞 0
收藏 0
连接costa

我有一些链接的数据JSON,我想知道如果并且仅当有第二个项时,如何向数组添加第二个项。

在我的例子中,在一篇文章中添加一个或两个合著者。

  script(type="application/ld+json").
    {
      "@context": "http://schema.org",
      "@type": "Article",
      "headline": "#{article.title}",
      "description": "#{article.description}",
      "author": [{
        "@type": "Person",
        "name": "#{article.author && article.author.name}",
        "givenName": "#{article.author && article.author.givenName}",
        "additionalName": "#{article.author && article.author.additionalName}",
        "familyName": "#{article.author && article.author.familyName}",
        "email": "#{article.author && article.author.email}",
        "jobTitle": "#{article.author && article.author.jobTitle}",
        "workLocation": "#{article.author && article.author.workLocation}",
        "worksFor": "Company",
        "image": "#{article.author && article.author.image}",
        "url": "#{article.author && article.author.url}",
        "sameAs": !{JSON.stringify(article.author && article.author.sameAs)}
      }],
      "datePublished": "#{article.date}",
      "dateModified": "#{article.updated || article.date}",
      "publisher": {
        "@type": "Organization",
        "name": "Company",
        "logo": {
          "@type": "ImageObject",
          "url": "...logo-url.jpg"
        }
      },
      "image": "#{article.image}",
      "url": "#{article.url}"
    }

这里的模板语言是pug。

那么我如何添加第二个人呢?

     "sameAs": !{JSON.stringify(article.author && article.author.sameAs)}
  }
  if (coauthor) return ,{author-2}
  ],
     "datePublished": "#{article.date}",
建议答案

一种(稍微迂回的)方法是使用未缓冲的代码块预先在javascript中构建模式对象,然后使用JSON.stringify().

假设您的数据结构为article.authors是作者数组:

-
  let jsonld = {
    '@context': 'http://schema.org',
    '@type': 'Article',
    'headline': article.title,
    'description': article.description,
    'datePublished': article.date,
    'dateModified': article.updated || article.date,
    'publisher': {
      '@type': 'Organization',
      'name': 'Company',
      'logo': {
        '@type': 'ImageObject',
        'url': '...logo-url.jpg'
      }
    },
    'image': article.image,
    'url': article.url
  }
  for (let i = 0; i < article.authors.length; i++) {
    jsonld.authors = jsonld.authors || []
    let author = {
      '@type': 'Person',
      'name': article.authors[i].name,
      'givenName': article.authors[i].givenName,
      'additionalName': article.authors[i].additionalName,
      'familyName': article.authors[i].familyName,
      'email': article.authors[i].email,
      'jobTitle': article.authors[i].jobTitle,
      'workLocation': article.authors[i].workLocation,
      'worksFor': 'Company',
      'image': article.authors[i].image,
      'url': article.authors[i].url,
      'sameAs': JSON.stringify(article.authors[i].sameAs
    }
    jsonld.authors.push(author)
  }

script(type="application/ld+json")= JSON.stringify(jsonld, null, 2)
👍 0