首页 > 解决方案 > 读取文件夹中的所有 JSON 并获取它们的字符串

问题描述

有一个包含很多 JSON 文件的文件夹,它们都有一个名为"name" I want to get their strings and turn them into a string like this的对象

name0=UsernameExample;name1=Flowers;name2=Test; ...

name 后面的数字是 json 的索引/计数,例如它的 name48,它是第 48 个 json 到目前为止,我只尝试从文件夹中读取 JSON,但我当然失败了

let s = "";
  fs.readdir('/tmp/userdb/', (files) => {
  files.each(file => {
    name = file[file.keys()[0]]; 
  })})

我已经可以转换这个

var other_users = (serialize({
      "sid0": 0,
      "name0": "user1",
      "pays0": "8521",
      "avatar0": "357",
      "onlinescore0": "50"
    }));

对此:

sid0=0;name0=user1;pays0=8521;avatar0=357;onlinescore0=50

有了这个常量

const serialize = obj =>
  Object.entries(obj).map(([k, v]) => `${k}=${v}`).join(';')

我想用这种方式将结果发送给用户

if (req.query.d === 'getRandomPlayers') {
    
    var sessionid = req.body.player_sid
    let user = require("./tmp/userdb/" + sessionid + ".json")
    
    var current_user = (serialize({
      player_name: user.name
    }));
      
    res.send("method_id=1665;" + current_user);
  }

这应该res.send("method_id=1665;" + current_user + thefinalresult); thefinalresult是这一切都应该去的。current_user和其他东西与这个问题无关。

标签: node.jsjsondatabase

解决方案


假设里面的示例JSON文件/tmp/userdb/具有以下结构,

{
  "53874745": {
    "avatar": "372",
    "name": "BILLY",
    "onlinescore": "1",
    "pays": "8758"
  }
}

您可以执行以下操作:

const { promisify } = require("util");
const fs = require("fs");
const path = require("path");

const readdir = promisify(fs.readdir);
const readFile = promisify(fs.readFile);

async function process(excludedSessionId) {
  try {
    const entries = [];

    // get a list of all `JSON` files
    const jsonFiles = await readdir(
      path.join(__dirname, "./tmp/userdb/")
    ).then(
      (files) => files.filter(
        (file) => path.extname(file) === ".json" && !file.includes(excludedSessionId)
      )
    );

    // iterate through a list of all `JSON` files & read their content
    for (const [index, file] of jsonFiles.entries()) {
      const content = await readFile(
        path.join(__dirname, "./tmp/userdb/", file)
      ).then(JSON.parse);

      // create an object for a new entry
      const key = `sid${index}`;
      const keyValue = Object.keys(content)[0];

      // use the `spread syntax` to include the rest of the
      // properties in a new entry 
      const entry = {
        [key]: keyValue,
        ...content[keyValue],
      };

      entries.push(entry);
    }

    console.log(entries[0]);
    // { 
    //    sid0: '53874745', 
    //    avatar: '372', 
    //    name: 'BILLY', 
    //    onlinescore: '1', 
    //    pays: '8758'
    //  }

    const result = entries.map((entry) => serialize(entry)).join(";");

    console.log(result);
    // sid0=53874745;avatar=372;name=BILLY;onlinescore=1;pays=8758;
    // sid1=154261758;avatar=480;name=JESSEY;onlinescore=30;pays=8521;

    return result;
  } catch (error) {
    console.error(error);
    throw error;
  }
}
process("154261742");

然后,如果您想在路由控制器的回调中使用此函数,您可以执行以下操作:

app.get("/user", (req, res) => {
  // ...
  const excludedSessionId = req.body.player_sid;

  process(excludedSessionId)
    .then(result => {
      res.send(result);
    })
    .catch(error => {
      res.status(500).send("Something went wrong.");
    });
});

参考:


推荐阅读