本文介绍了如何使用jq扁平化字符串编码的json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下json.

[
    {
        "myfield1": "foo",
        "myfield2": "{\"field1\":6366987, \"field2\":5501072}"
    },
    {
        "myfield1": "bar",
        "myfield2": "{\"field1\":123456, \"field2\":123456}"
    }
]

并希望得到...

[
    {
        "myfield1": "foo",
        "field1": 6366987,
        "field2": 5501072
    },
    {
        "myfield1": "foo",
        "field1": 123456,
        "field2": 123456
    },
]

到目前为止,我知道了...

So far I got this...

jq'[.[0] | {myfield1:.myfield1,myfield2:.myfield2 | fromjson}]'

jq '[.[0] | {myfield1: .myfield1, myfield2: .myfield2|fromjson}]'

但这意味着我必须指定每个json字段,而且它不能使json编码的字符串变平.

But this means I have to specify each json field plus it doesn't flatten the json encoded string.

我想我是这么做的...

I think I got it with this...

jq'[.[0] | with_entries(select(.key!="myfield2"))+(.myfield2 | fromjson)]'

jq '[.[0]|with_entries(select(.key != "myfield2"))+(.myfield2|fromjson)]'

这有意义吗?

推荐答案

您说对了,解决方案涉及fromjson,但是更简单,更直接,更有效的方法如下:

You're right that the solution involves fromjson, but a simpler, more direct, and more efficient approach would be as follows:

map( { myfield1 } + ( .myfield2 | fromjson ) )

如果要保留"myfield2"以外的所有字段,请考虑:

If you want to retain all the fields except "myfield2", consider:

map( del(.myfield2) + ( .myfield2 | fromjson ) )

这篇关于如何使用jq扁平化字符串编码的json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 07:05