将嵌套的JSON字符串转换为JSON

时间:2017-12-21 10:50:05

标签: javascript json node.js

我正在使用AEM内容API并且它提供了JSON结构,但对于特定的嵌套节点(如链接),它会提供响应的JSON字符串。

示例有效负载 -

{
  "Page Title": "Home",
  "Page Description": "Sample Description",
  "Key Words": "test1, test2, test 3",
  "sections": [{
    "Lineup": {
      "title": "Our Project Family",
      "strategy": [{
        "title": "ASHJASH BASED",
        "description": "This is a short description",
        "links": ["{\"text\":\"income\",\"href\":\"/content/dam/usa/pdf/2017m_10.pdf\",\"desc\":\"This is a short description\"}", "{\"text\":\"Real Return\",\"href\":\"/content/dam/usa/pdf/singlepg.pdf\",\"desc\":\"This is a short description why to consider this\"}"],
        "moreLink": "/content/us/home"
      }, {
        "title": "ALLOCATION",
        "description": "This is a short description",
        "links": ["{\"text\":\"fund\",\"href\":\"/content/dam/usa/pdf/2017m_10.pdf\",\"desc\":\"This is a short description\"}", "{\"text\":\"ETF\",\"href\":\"/content/dam/usa/pdf/2017m_10.pdf\",\"desc\":\"This is a short description\"}", "{\"text\":\"Active/Passive\",\"href\":\"/content/dam/usa/pdf/sat02017m_10.pdf\",\"desc\":\"This is a short description\"}"],
        "moreLink": "/content/us/home"
      }]
    }
  }]
}

在此有效内容中,嵌套链接部分是JSON字符串。

在我的API中,当我使用有效负载时,我应该能够将纯JSON对象发送到我的前端。这个结构在所有端点上都是不同的,所以我想要一种通用的方法将整个对象转换为JSON。

1 个答案:

答案 0 :(得分:0)

然后解析然后将内容链接到JSON并将结果从node.js服务器响应给用户:Here正在运行示例。

//ES6
let res = {
  "Page Title": "Home",
  "Page Description": "Sample Description",
  "Key Words": "test1, test2, test 3",
  "sections": [{
    "Lineup": {
      "title": "Our Project Family",
      "strategy": [{
        "title": "ASHJASH BASED",
        "description": "This is a short description",
        "links": ["{\"text\":\"income\",\"href\":\"/content/dam/usa/pdf/2017m_10.pdf\",\"desc\":\"This is a short description\"}", "{\"text\":\"Real Return\",\"href\":\"/content/dam/usa/pdf/singlepg.pdf\",\"desc\":\"This is a short description why to consider this\"}"],
        "moreLink": "/content/us/home"
      }, {
        "title": "ALLOCATION",
        "description": "This is a short description",
        "links": ["{\"text\":\"fund\",\"href\":\"/content/dam/usa/pdf/2017m_10.pdf\",\"desc\":\"This is a short description\"}", "{\"text\":\"ETF\",\"href\":\"/content/dam/usa/pdf/2017m_10.pdf\",\"desc\":\"This is a short description\"}", "{\"text\":\"Active/Passive\",\"href\":\"/content/dam/usa/pdf/sat02017m_10.pdf\",\"desc\":\"This is a short description\"}"],
        "moreLink": "/content/us/home"
      }]
    }
  }]
}

res.sections = res.sections.map(
  section => {
    section.Lineup.strategy = section.Lineup.strategy.map(
      strategy => {
        strategy.links = strategy.links.map(
          link => JSON.parse(link)
        )

        return strategy;
      }
    )

    return section;
  }
)
相关问题