在bash中将行转换为json [英] converting lines to json in bash

查看:103
本文介绍了在bash中将行转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将列表转换为JSON数组.我正在为此寻找jq,但是示例大部分是关于解析JSON(而不是创建JSON)的.知道会发生适当的转义会很高兴.我的列表是单行元素,因此新行可能是最好的定界符.

I would like to convert a list into JSON array. I'm looking at jq for this but the examples are mostly about parsing JSON (not creating it). It would be nice to know proper escaping will occur. My list is single line elements so the new line will probably be the best delimiter.

推荐答案

我也试图将一堆线转换为JSON数组,并且一直停滞不前,直到我意识到-s是我唯一的方法即使在jq表达式中一次处理多行,即使那意味着我不得不手动解析换行.

I was also trying to convert a bunch of lines into a JSON array, and was at a standstill until I realized that -s was the only way I could handle more than one line at a time in the jq expression, even if that meant I'd have to parse the newlines manually.

jq -R -s -c 'split("\n")' < just_lines.txt

  • -R读取原始输入
  • -s以单个字符串读取所有输入
  • -c不能很好地打印输出
    • -R to read raw input
    • -s to read all input as a single string
    • -c to not pretty print the output
    • 轻松自在.

      我在jq≥1.4上,显然是在引入split内置组件时.

      I'm on jq ≥ 1.4, which is apparently when the split built-in was introduced.

      这篇关于在bash中将行转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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