将文件读入JSON [英] Read files into JSON

查看:94
本文介绍了将文件读入JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取几个文件(index.html,style.css,main.js)以创建用于上传的JSON有效负载.

I want to read in several files (index.html, style.css, main.js) to create a JSON payload for upload.

我知道使用nodejs,我可以开始创建自己想要的东西:

I know with nodejs, I can begin to create what I want like so:

var fs = require('fs');
fs.readFile('index.html', 'utf8', function (err, data) {
  if (err) throw err;
  out = JSON.stringify({"html": data});
  console.log(out);
});

尽管我该如何使用 jq 做到这一点?

Though how do I do that with jq?

推荐答案

以下显示了一种处理多个文本文件的方法:

One way to handle multiple text files is illustrated by the following:

(jq -Rs . a.txt ; jq -sR . b.txt) | jq -s
[
  "1\n2\n",
  "3\n4\n"
]

因此,在您的情况下,您将执行以下操作:

So in your case you would do something like this:

(jq -Rs '{ html: . }' index.html; \
 jq -Rs '{ javascript: . }' main.js; \
 jq -Rs '{ css: . }' style.css) |\
 jq -s add

也就是说,将每个文本文件分别转换为JSON字符串,然后将这些字符串传递给jq.这样做的好处是不需要jq 1.5,但是如果确实有jq 1.5,则使用过滤器inputs的解决方案可能会更好.

That is, convert each text file to a JSON string separately, and then pipe these strings to jq. This has the advantage of not requiring jq 1.5, but if you do have jq 1.5, then a solution using the filter inputs might be preferable.

这篇关于将文件读入JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆