简体   繁体   English

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

[英]Save new JSON data to new json file

Let me preface that I'm a total js noob, so thank you for your help. 让我作为我的一个总的菜鸟,谢谢您的帮助。

I am using the randomuser.me api to create a list of users. 我正在使用randomuser.me api创建用户列表。 However, it only gives me the names in lowercase. 但是,它只为我提供小写的名称。 So I used this script (with the help of someone else) to capitalize the names. 因此,我使用此脚本(在其他人的帮助下)将名称大写。 Now I want to take that new data and create a json file. 现在,我要获取新数据并创建一个json文件。 From what I've read, I need to use node.js, but have no idea how to run it properly. 根据我的阅读,我需要使用node.js,但不知道如何正确运行它。 I've done npm install and installed this module: https://github.com/jprichardson/node-jsonfile 我已经完成npm安装并安装了以下模块: https : //github.com/jprichardson/node-jsonfile

I'm also using firebase to put the data into a database and hosting it. 我还使用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!");
        //     }
        // });

  });

Can you js wizards point me in the right direction? js向导可以为我指出正确的方向吗? Thank you! 谢谢!

If you are just trying to test out your own data, using consolesave.js for Chrome can save you a lot of time. 如果您只是想测试自己的数据,那么使用Chrome的consolesave.js可以节省大量时间。 When I'm initially setting up projects and testing data I've retrieved via ajax and then parsed and re-written, this small script lets you write JSON directly from Chrome (to your downloads folder). 当我最初设置项目和测试数据时,我已经通过ajax检索了这些数据,然后对其进行了解析和重写,此小脚本可让您直接从Chrome(至您的下载文件夹)编写JSON。 I'm not sure where I got this file, but one source is this github repo. 我不确定我在哪里得到这个文件,但是这个github回购就是其中一个来源。 https://github.com/bgrins/devtools-snippets/blob/master/snippets/console-save/console-save.js 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> 

FINALLY figured it out. 最终想通了。 After several hours of trial and error, I got it to work! 经过数小时的反复试验,我终于开始工作了! Probably messy and horrible code, but this was a hack project from the get-go anyway. 可能是凌乱和可怕的代码,但这仍然是一开始的hack项目。 Here's my final code: 这是我的最终代码:

// 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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM