如何用javascript写入json文件?

时间:2016-06-16 09:39:59

标签: javascript json node.js

我有json文件

{
    "username1": "user1",
    "password1": "***",

    "username2": "user2",
    "password2": "****",

    "username3": "user3",
    "password3": "*****"
}

我正在读这样的文件:

var fs = require('fs');
var contents = fs.readFileSync('./actions/writeTo.json');
var jsonContent = JSON.parse(contents);            
console.log(jsonContent.username2);

但我无法弄清楚如何写这个文件,说我想更新username3。我该怎么做?

5 个答案:

答案 0 :(得分:1)

你所做的与你所做的完全相反。

您使用from __future__ import print_function class Intersector(object): def __init__(self, relation): self.relation = relation def intersect(self, a, b): a_classes = self.get_equivalence_classes(a) print('Groups of A:', a_classes) b_classes = self.get_equivalence_classes(b) print('Groups of B:', b_classes) return self.intersect_classes(a_classes, b_classes) def get_equivalence_classes(self, elements): eq_classes = [] for element in elements: match = False for eq_class in eq_classes: if self.relation(element, eq_class[0]): eq_class.append(element) match = True break if not match: eq_classes.append([element]) return eq_classes def intersect_classes(self, a, b): def search_in_B(g): for h in b: if self.relation(g[0], h[0]): return h result = [] for g in a: h = search_in_B(g) if h is not None: result.append(g+h) print('Intersection:', result) return result if __name__ == '__main__': A = set([4, 2, 1, 7, 0]) B = set([1, 13, 23, 12, 62, 101, 991, 1011, 1337, 66, 666]) print('A:', A) print('B:', B) print(79*'-') print('Intersection with respect to the relation:') print('a and b have the same remainder divided by 5') intersection = Intersector(lambda x, y : x % 5 == y % 5).intersect(A, B) reduced = [c[0] for c in intersection] print('Intersection reduced to representatives:', reduced) print(79*'-') print('Intersection with respect to the relation:') print('a and b have the same remainder divided by 7') intersection = Intersector(lambda x, y : x % 7 == y % 7).intersect(A, B) reduced = [c[0] for c in intersection] print('Intersection reduced to representatives:', reduced) 将数据结构转换为JSON。然后使用A: set([0, 1, 2, 4, 7]) B: set([1, 66, 101, 12, 13, 1011, 23, 1337, 666, 62, 991]) ------------------------------------------------------------------------------- Intersection with respect to the relation: a and b have the same remainder divided by 5 Groups of A: [[0], [1], [2, 7], [4]] Groups of B: [[1, 66, 101, 1011, 666, 991], [12, 1337, 62], [13, 23]] Intersection: [[1, 1, 66, 101, 1011, 666, 991], [2, 7, 12, 1337, 62]] Intersection reduced to representatives: [1, 2] ------------------------------------------------------------------------------- Intersection with respect to the relation: a and b have the same remainder divided by 7 Groups of A: [[0, 7], [1], [2], [4]] Groups of B: [[1, 666], [66, 101, 1011], [12], [13, 62], [23], [1337], [991]] Intersection: [[0, 7, 1337], [1, 1, 666], [2, 23], [4, 991]] Intersection reduced to representatives: [0, 1, 2, 4] 将其写入文件。

答案 1 :(得分:0)

var fs = require('fs');
var contents = fs.readFileSync('./actions/writeTo.json');
var jsonContent = JSON.parse(contents);            
console.log(jsonContent.username2);

jsonContent.username3 = 'Changed';
jsonContent.username4 = 'New User';

var dest = '../file.json';

var fd = fs.createWriteStream(dest, {
    flags: 'w',
    autoClose: true
});

fd.write(JSON.stringify(jsonContent));
fd.end('\n');
fd.on('finish', () => {
    //Handle success
}).on('error', (err) => { // Handle errors
    fs.unlink(dest); // Delete the file async. (But we don't check the result)
});

答案 2 :(得分:0)

首先,我希望这仅用于教育目的,并且您不打算以这种方式管理用户帐户,将明文密码存储在json文件中。

其次,您似乎滥用了JSON的结构。为什么在拥有数组时拥有user1user2user3键?如果你像这样安排这些数据会好得多:

{
    "users": [
        {
            "username": "Alice",
            "anything-but-not-plaintext-password": "Puppies and kittens"
        },
        {
            "username": "Bob",
            "anything-but-not-plaintext-password": "Cheese nuggets"
        }
    ]
}

最后,您可以使用fs.writeFileSync

将json写入nodejs中的文件
var fs = require('fs');
var jsonContent = {}; // Here is your loader and modifier code
var jsonString = JSON.stringify(jsonContent, null, 4); // Pretty printed
fs.writeFileSync("./actions/writeTo.json", jsonString);

但是,这是你不能处理用户凭据的方式。以下是关于该主题的非常好的教程:Node.js authentication series: Passport local strategy using email and password.

答案 3 :(得分:0)

您可以使用以下代码:

jsonContent.username3 = 'NewUsername';

var body = JSON.stringify(jsonContent);
var localPath = './actions/writeTo.json';
fs.writeFile(localPath,body,function(err){});

答案 4 :(得分:0)

npm install jsonfile

var jsonfile = require('jsonfile');  
var config = require('../support/config.json');  

function writeToConfig(name, fileObj) {  

fileObj.username3 = name;
//console.log('This is to WriteFile Stringified fileObj:' +'\n\n' + JSON.stringify(fileObj) + '\n\n');

jsonfile.writeFile(filePath, fileObj, function (err) {
    if (err) {
        console.error(err);
    }
});
}

现在您可以使用此功能并将其命名为

writeToConfig(finalRandomName, config);