创建.json文件并使用JavaScript将数据存储在其中? [英] Creating .json file and storing data in it with JavaScript?
问题描述
我有一个在node.js
上运行的后端JavaScript
文件.它使用async.series
做一些事情,并产生最终字典(对象),以及我在前端需要的数据.我现在如何读取.json
文件并将其转换为JavaScript
对象,但是我不知道如何使用后端JavaScript
创建.json
文件以及如何在其中存储一些数据.
I have a back-end JavaScript
file that runs on node.js
. It do some stuff using async.series
and yields the final dictionary(object) with data I need on my front-end. I now how to read a .json
file and convert it into the JavaScript
object, but I do not know create .json
file with back-end JavaScript
and how to store some data in it.
任何人都可以告诉我正确的方法.
Could anyone please tell me the right way to do this.
这是我需要转换并存储到.json
文件的字典(对象).
Here is the dictionary(object) that I need to convert and store to the .json
file.
var dict = {"one" : [15, 4.5],
"two" : [34, 3.3],
"three" : [67, 5.0],
"four" : [32, 4.1]};
推荐答案
简单!您可以将其转换为JSON(作为字符串).
Simple! You can convert it to a JSON (as a string).
var dictstring = JSON.stringify(dict);
要在NodeJS中保存文件,
To save a file in NodeJS:
var fs = require('fs');
fs.writeFile("thing.json", dictstring);
此外,javascript中的对象使用冒号,而不等于:
Also, objects in javascript use colons, not equals:
var dict = {"one" : [15, 4.5],
"two" : [34, 3.3],
"three" : [67, 5.0],
"four" : [32, 4.1]};
这篇关于创建.json文件并使用JavaScript将数据存储在其中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!