在jq中移动嵌套值

时间:2019-07-16 11:05:13

标签: json jq

我有一个像这样的json:

public partial class Form1 : Form
{
    static readonly HttpClient _hcli = new HttpClient();

    public Form1()
    {
        InitializeComponent();
    }

    private static string log;
    private async void button1_Click(object sender, EventArgs e)
    {
        log = "";
        await M3();
        MessageBox.Show(log);
    }

    static async Task<string> M3()
    {
        LogBefore(nameof(M3));
        var str = await M2();
        LogAfter(nameof(M3));
        return str;
    }

    static async Task<string> M2()
    {
        LogBefore(nameof(M2));
        var str = await M1();
        LogAfter(nameof(M2));
        return str;
    }

    static async Task<string> M1()
    {
        LogBefore(nameof(M1));
        var str = await _hcli.GetStringAsync("http://mtkachenko.me").ConfigureAwait(false);
        LogAfter(nameof(M1));
        return str;
    }

    static void LogBefore(string method)
    {
        log += $"before {method} {Thread.CurrentThread.ManagedThreadId} {SynchronizationContext.Current == null}, ";
    }

    static void LogAfter(string method)
    {
        log += $"after {method} {Thread.CurrentThread.ManagedThreadId} {SynchronizationContext.Current == null}, ";
    }
}

我想这样输出

before M3 1 False
before M2 1 False
before M1 1 False
after M1 12 True //sync.context skipped
after M2 1 False //sync.context restored
after M3 1 False //sync.context restored

{ "key_1": { "type": "string", "value": "foo" }, "key_2": { "type": "string", "value": "bar" } } 将为我提供值:

{
  "key_1": "foo",
  "key_2": "bar"
}

jq '.[].value'会给我

"foo"
"bar"

所以我不确定。

2 个答案:

答案 0 :(得分:5)

由于该任务需要映射顶级键的值,因此请注意map_values

map_values(.value)

您还可以使用with_entries,如果您也想操作顶级键,这可能很有意义:

with_entries( .value |= .value )

答案 1 :(得分:0)

或者,也可以使用基于unix步行路径的实用程序 jtc

1。一种方法是在记忆密钥的同时对每个value进行交谈,然后应用模板插值以按要求的格式显示记录

bash $ <foobar.json jtc -w'[:]<K>k[value]' -T'{"{K}":{{}}}' -jjll
{
   "key_1": "foo",
   "key_2": "bar"
}
bash $ 

2。但是,更优雅的方法是使用内部value更新顶部记录:

bash $ <foobar.json jtc -w[:] -u[:][value]
{
   "key_1": "foo",
   "key_2": "bar"
}
bash $ 

3。或者,也可以将每个内部value换成最高记录:

bash $ <foobar.json jtc -w[:] -w[:][value] -s
{
   "key_1": "foo",
   "key_2": "bar"
}
bash $ 

PS>披露:我是jtc-用于JSON操作的shell cli工具的创建者