博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用Node.js解析JSON
阅读量:2501 次
发布时间:2019-05-11

本文共 2729 字,大约阅读时间需要 9 分钟。

If you have data as part of a string, the best way to parse it is by using the JSON.parse method that’s part of the JavaScript standard since ECMAScript 5, and it’s provided by , the JavaScript engine that powers .

如果您将数据作为字符串的一部分,则解析它的最佳方法是使用JSON.parse方法,该方法是ECMAScript 5以来JavaScript标准的一部分,并且由提供,它是为提供支持JavaScript引擎。

Example:

例:

const data = '{ "name": "Flavio", "age": 35 }'try {  const user = JSON.parse(data)} catch(err) {  console.error(err)}

Note that JSON.parse is synchronous, so the more the JSON file is big, the more time your program execution will be blocked until the JSON is finished parsing.

请注意, JSON.parse是同步的,因此JSON文件越大,在JSON完成解析之前,您的程序执行将被阻塞的时间越长。

You can process the JSON asynchronously by wrapping it in a and a setTimeout call, which makes sure parsing takes place in the next iteration of the event loop:

您可以通过将其包装在和setTimeout调用中来异步处理JSON,以确保解析在事件循环的下一次迭代中进行:

const parseJsonAsync = (jsonString) => {  return new Promise(resolve => {    setTimeout(() => {      resolve(JSON.parse(jsonString))    })  })}const data = '{ "name": "Flavio", "age": 35 }'parseJsonAsync(data).then(jsonData => console.log(jsonData))

If your JSON is in a file instead, you first have to read it.

如果您的JSON位于文件中,则首先必须阅读它。

A very simple way to do so is to use require():

一种非常简单的方法是使用require()

const data = require('./file.json')

Since you used the .json extension, require() is smart enough to understand that, and parse the JSON in the data object.

由于您使用的是.json扩展名,所以require()足够聪明,可以理解它并解析data对象中的JSON。

One caveat is that file reading is synchronous. Plus, the result of the require() call is cached, so if you call it again because you updated the file, you won’t get the new contents until the program exits.

一个警告是文件读取是同步的。 另外,require()调用的结果将被缓存,因此,如果由于更新文件而再次调用它,则在程序退出之前您将无法获得新内容。

This feature was provided to use a JSON file for the app configuration, and it’s a perfectly valid use case.

提供此功能是为了使用JSON文件进行应用程序配置,这是一个非常有效的用例。

You can also read the file manually, using fs.readFileSync:

您也可以使用fs.readFileSync手动读取文件:

const fs = require('fs')const fileContents = fs.readFileSync('./file.json', 'utf8')try {  const data = JSON.parse(fileContents)} catch(err) {  console.error(err)}

This reads the file synchronously.

这将同步读取文件。

You can also read the file asynchronously using fs.readFile, and this is the best option. In this case, the file content is provided as a callback, and inside the callback you can process the JSON:

您也可以使用fs.readFile异步读取文件,这是最好的选择。 在这种情况下,文件内容作为回调提供,并且在回调内部您可以处理JSON:

const fs = require('fs')fs.readFile('/path/to/file.json', 'utf8', (err, fileContents) => {  if (err) {    console.error(err)    return  }  try {    const data = JSON.parse(fileContents)  } catch(err) {    console.error(err)  }})

翻译自:

转载地址:http://waqgb.baihongyu.com/

你可能感兴趣的文章
OCO订单(委托)
查看>>
学习笔记_vnpy实战培训day06
查看>>
回测引擎代码分析流程图
查看>>
Excel 如何制作时间轴
查看>>
matplotlib绘图跳过时间段的处理方案
查看>>
vnpy学习_04回测评价指标的缺陷
查看>>
iOS开发中遇到的问题整理 (一)
查看>>
Linux(SUSE 12)安装jboss4并实现远程访问
查看>>
Neutron在给虚拟机分配网络时,底层是如何实现的?
查看>>
netfilter/iptables全攻略
查看>>
Overlay之VXLAN架构
查看>>
Eclipse : An error occurred while filtering resources(Maven错误提示)
查看>>
在eclipse上用tomcat部署项目404解决方案
查看>>
web.xml 配置中classpath: 与classpath*:的区别
查看>>
suse如何修改ssh端口为2222?
查看>>
详细理解“>/dev/null 2>&1”
查看>>
suse如何创建定时任务?
查看>>
suse搭建ftp服务器方法
查看>>
centos虚拟机设置共享文件夹并通过我的电脑访问[增加smbd端口修改]
查看>>
文件拷贝(IFileOperation::CopyItem)
查看>>