将新的JSON数据保存到新的json文件

时间:2018-01-15 21:34:13

标签: javascript json node.js

让我作为一个总js noob的序言,所以谢谢你的帮助。

我使用randomuser.me api创建用户列表。但是,它只给我小写的名字。所以我使用这个脚本(在其他人的帮助下)来大写这些名字。现在我想获取新数据并创建一个json文件。根据我的阅读,我需要使用node.js,但不知道如何正确运行它。我已经完成了npm install并安装了这个模块:https://github.com/jprichardson/node-jsonfile

我还使用firebase将数据放入数据库并托管它。

//init firebasejs
var config = {
    apiKey: "AIzaSyD0F_1-ynUdzpEkQADrs6BbXUInFCkpBdM",
    authDomain: "random-users.firebaseapp.com",
    databaseURL: "https://random-users.firebaseio.com",
    projectId: "random-users",
    storageBucket: "random-users.appspot.com",
    messagingSenderId: "675456550116"
};
firebase.initializeApp(config);

var database = firebase.database();

var fs = require('fs');

var jsonfile = require('jsonfile')
var file = '/tmp/data.json'

//fuunction to capitalize strings
function capitalize(text) {
    return (!text || !text.length) ?
        text :
        (text[0].toUpperCase() + text.slice(1));
}


$.get("https://randomuser.me/api/ results=20&nat=us&inc=name,gender,picture&format=pretty",
    function(data) {
        if (!data || !data.results)
            return;

        //going through 'data' and capitalizing name and gender
        data.results.forEach(function(user) {
            if (user.name) {
                for (var name in user.name) {
                    user.name[name] = capitalize(user.name[name]);
                }
            }
            if (user.gender) {
                user.gender = capitalize(user.gender);
            }
        });

        console.log(data);

        //write new data to firebase
        database.ref().set(data);

        //write json file?
        var result = JSON.stringify(data, null, 4);
        $('#randomUsers').html(result);

        jsonfile.writeFile(file, data, {spaces: 2}, function(err) {
            console.error(err)
        })


        // var fs = require("fs");
        // fs.writeFile("randomUsers.json", result, function(err) {
        //     if (err) {
        //         return console.log(err);
        //     } else {
        //         console.log("The file was saved!");
        //     }
        // });

  });

你能和巫师指出我正确的方向吗?谢谢!

2 个答案:

答案 0 :(得分:1)

如果您只是想测试自己的数据,那么在Chrome上使用consolesave.js可以为您节省大量时间。当我最初设置项目和测试数据时,我通过ajax检索然后解析并重新编写,这个小脚本允许您直接从Chrome(到您的下载文件夹)编写JSON。我不确定我在哪里获得这个文件,但是有一个来源是这个github repo。 https://github.com/bgrins/devtools-snippets/blob/master/snippets/console-save/console-save.js

function capitalize(text) {
    return (!text || !text.length) ?
        text :
        (text[0].toUpperCase() + text.slice(1));
}



(function(console){

    console.save = function(data, filename){
      
        console.log('data is '+data);
        if(!data) {
            console.error('Console.save: No data')
            return;
        }

        if(!filename) filename = 'console'

        if(typeof data === "object"){
            data = JSON.stringify(data, undefined, 4)
        }

        var blob = new Blob([data], {type: 'text/json'}),
            e    = document.createEvent('MouseEvents'),
            a    = document.createElement('a')

        a.download = filename+ '.json'
        a.href = window.URL.createObjectURL(blob)
        a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
        a.dispatchEvent(e)
    }
})(console)

$.ajax({
 url: 'https://randomuser.me/api/?results=20&nat=us&inc=name,gender,picture&format=pretty',
    type : 'GET',
    dataType:'json',
    success : function(data) {  
        if (!data || !data.results) {
          console.log('no data');
          return
         }
         console.log('got your data')
        //going through 'data' and capitalizing name and gender
        data.results.forEach(function(user) {
            if (user.name) {
                for (var name in user.name) {
                    user.name[name] = capitalize(user.name[name]);
                }
            }
            if (user.gender) {
                user.gender = capitalize(user.gender);
            }
        });

        console.log(data);
        console.save(JSON.stringify(data),'test_data.json');
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

最终想通了。经过几个小时的反复试验,我得到了它的工作!可能是凌乱和可怕的代码,但无论如何这是一个开始的黑客项目。这是我的最终代码:

// initialize firebase------------------------------------
var firebase = require('firebase');

var config = {
    apiKey: "AIzaSyBjS4dUaqPLhggmdF9hrIwQTH4i4QwjpR4",
    authDomain: "my-user-generator.firebaseapp.com",
    databaseURL: "https://my-user-generator.firebaseio.com",
    projectId: "my-user-generator",
    storageBucket: "my-user-generator.appspot.com",
    messagingSenderId: "317975340395"
  };
var app = firebase.initializeApp(config);
var database = firebase.database();
//-------------------------------------------------------

const got = require('got');
var each  = require('foreach');
var jsonfile = require('jsonfile')

//function to capitalize text
function capitalize(text) {
    return (!text || !text.length) ?
    text :
    (text[0].toUpperCase() + text.slice(1));
}

got('https://randomuser.me/api/?results=20&nat=us&inc=name,gender,picture&format=pretty', {json: true}).then(response => {

        var data = response.body;

        //capitalize names and gender
        each(data.results, function(user) {
            if (user.name) {
                for (var name in user.name) {
                    user.name[name] = capitalize(user.name[name]);
                }
            }
            if (user.gender) {
                user.gender = capitalize(user.gender);
            }
        });

        //create json file
        var file = 'users.json';

        jsonfile.writeFile(file, data, {spaces: 4, EOL: '\r\n'}, function(err) {
            console.error(err)
        });
        console.log(data);

        //write new data to firebase
        database.ref().set(data);

}).catch(error => {
    console.log(error.response.body);
});