gpt4 book ai didi

ruby - 在终端上使用 Ruby 美化 JSON 数据

转载 作者:太空宇宙 更新时间:2023-11-03 16:35:00 39 4
gpt4 key购买 nike

我之前使用 Python 像这样漂亮地输出 JSON 数据:

python -mjson.tool input.json

我想使用 Ruby 获得类似的输出。我是这样做的:

ruby -rrubygems -e 'require "json"; ARGV.each { |f| print JSON.pretty_generate(JSON.load(File.open(f))) }'  input.json

这对于一个小的 shell 命令来说已经很多了。你能推荐一个更好的方法吗?

最佳答案

您可以缩短脚本:

# ruby 1.9.2
ruby -rjson -e 'ARGF.each(nil) {|f| puts JSON.pretty_generate(JSON.parse(f)) }' file1 file2

# ruby 1.8.7
ruby -rubygems -e 'require "json"; ARGF.each(nil) {|f| puts JSON.pretty_generate(JSON.parse(f)) }' file1 file2

ARGF is a stream designed for use in scripts that process files given as command-line arguments or passed in via STDIN.

我将 nil 传递给 ARGF#each 方法以按文件而不是按行拆分 ARGF(#each 的默认行为)。

关于ruby - 在终端上使用 Ruby 美化 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9110028/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com