【问题标题】:How to print JSON data in nodejs如何在nodejs中打印JSON数据
【发布时间】:2018-11-30 16:36:40
【问题描述】:

如何在nodejs json中打印JSON是

  {"errors":[
    {"location":"body","param":"email","value":"q","msg":"must be a Email"},{"location":"body","param":"password","value":"q","msg":"5 chars long"}]
    }

我的功能

function handleResponse(response) {

        return response.text().then( text => {
            console.log(text);
        });

        return Promise.reject(response);

}

console.log(text) 生成上述 json 数据,如何仅检索 msg 并在我的 reactjs 中打印

【问题讨论】:

  • 您正在寻找JSON.parse()
  • 我需要这个 json 的 msg
  • text.error.map((e)=> console.log(e.msg)) 我认为会为你做的
  • errors 是一个数组,因此您可以使用 map() 循环每个项目并从中打印 msg。
  • console.log(JSON.parse(text).errors.map(error => error.msg));

标签: javascript node.js reactjs express


【解决方案1】:

我希望我已经理解了这个问题。

如果您只想从服务器的 JSON 响应中获取消息字段,您只需要以这种方式 map 您的数组:

function handleResponse (textRes) {
  var jsonRes = {}
  var messages = []

  try {
    jsonRes = JSON.parse(textRes)
  }
  catch (e) {
    return Promise.reject(e)
  }

  messages = jsonRes.errors.map(function (error) {
    return error.msg
  })

  return Promise.resolve(messages)    
}

无论如何,您可以使用一些 npm 包来自动解析响应。我建议cross-fetch:

const fetch = require('cross-fetch')
const API_ENDPOINT = '/api/v1/test-endpoint'

function fetchData () {
  return fetch(API_ENDPOINT)
    .then(function (res) {
      return res.json()
    })
    .then(function (jsonRes) {
      messages = jsonRes.errors.map(function (error) {
        return error.msg
      })

      return Promise.resolve(messages)    
    })
    .catch(function (err) {
      //  Catch the error here or let the reject propagate
      //  to the parent function
    })

}

【讨论】:

    猜你喜欢
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    相关资源
    最近更新 更多