我正在尝试读取文本文件,并使用Node JS将其转换为javascript对象。我的文件如下所示:
Package: libseccomp2
Depends: libc6 (>= 2.14)
Description: high level interface to Linux seccomp filter
This library provides a high level interface to constructing, analyzing
and installing seccomp filters via a BPF passed to the Linux Kernel's
prctl() syscall.
Package: libperl5.26
Depends: libbz2-1.0, libc6 (>= 2.23), libdb5.3, libgdbm-compat4, libgdbm5 (>= 1.12), zlib1g (>= 1:1.2.2.3), perl-modules-5.26 (>= 5.26.1-6ubuntu0.3)
Description: shared Perl library
This package contains the shared Perl library, used by applications
which embed a Perl interpreter.
.
It also contains the architecture-dependent parts of the standard
library (and depends on perl-modules-5.26 which contains the
architecture-independent parts).
我想这样输出:
[{
Package: "libseccomp2",
Depends: ["libc6"]
Description: "high level interface to Linux seccomp filter
This library provides a high level interface to constructing, analyzing
and installing seccomp filters via a BPF passed to the Linux Kernel's
prctl() syscall."
},
{
Package: "libperl5.26",
Depends: ["libbz2-1.0", "libc6"]
Description: "high level interface to Linux seccomp filter
This library provides a high level interface to constructing, analyzing
and installing seccomp filters via a BPF passed to the Linux Kernel's
prctl() syscall."
}]
这是我到目前为止所拥有的,但是一直在给我错误。预先感谢您的帮助
fs.readFile('file.txt', "utf8", (err, data) => {
if (err) {
console.error(err)
return
}
let obj = {};
let line = data.toString().split("\n");
for (let i = 0; i<line.length; i++) {
let newLine = line[i].split(":");
obj[newLine[0]] = newLine[1].split(" ");
}
console.log(obj);
})
您的源文件看起来像是从YAML文件派生的。如果格式正确,则可以使用“ yaml”之类的npm库将文件直接解析为JS对象。
格式正确的YAML文件如下:
-
Package: libseccomp2
Depends: libc6 (>= 2.14)
Description: high level interface to Linux seccomp filter
This library provides a high level interface to constructing, analyzing and installing seccomp filters via a BPF passed to the Linux Kernel's prctl() syscall.
-
Package: libperl5.26
Depends: libbz2-1.0, libc6 (>= 2.23), libdb5.3, libgdbm-compat4, libgdbm5 (>= 1.12), zlib1g (>= 1:1.2.2.3), perl-modules-5.26 (>= 5.26.1-6ubuntu0.3)
Description: shared Perl library
This package contains the shared Perl library, used by applications
which embed a Perl interpreter.
.
It also contains the architecture-dependent parts of the standard
library (and depends on perl-modules-5.26 which contains the
architecture-independent parts).
我会先检查您的源文本文件是否可以生成为正确的YAML,或者如果您被当前文本文件所困扰,请尝试使用YAML validator将其编辑为正确的YAML。