jq:将对象中的数组映射到另一个对象,同时保留父键并添加新键

时间:2019-03-28 10:57:59

标签: json jq

我想映射以下结构

    private IEnumerator SetUserNameToTheTop()
    {
        while (ux.GetCurrentUser() == null && (DateTime.Now - dataTime).TotalSeconds < 15)
        {
            pendingTxt.text = (DateTime.Now - dataTime).TotalSeconds.ToString();
            Debug.Log("WAIT FOR ERROR");
            yield return new WaitForSeconds(1);
        }
        if (ux.GetCurrentUser() != null && ux.GetCurrentUser().userName != "")
        {
            ActivateMenu();
        }
        else
        {
            PENDING_MSG = "USER WASN'T FOUND, TRY TO SIGN UP FIRST";
            pendingTxt.text = PENDING_MSG;
            isFailed = true;
            FBButtons.SetActive(true);
        }
    }

进入此

{
    "id" : "OUTER_ID",
    "name" : "OUTER_NAME"
    "items" : [ 
        {   
            "id" : "INNER_ID_1",
            "name" : "INNER_NAME_1",
        },
        {   
            "id" : "INNER_ID_2",
            "name" : "INNER_NAME_2",
        }
    ]   
}

因此,对于初始{ "payload": [ { "key" : "INNER_NAME_1_KEY", "data" : { "id" : "OUTER_ID", "name" : "OUTER_NAME", "items" : [ { "id" : "INNER_ID_1", "name" : "INNER_NAME_1" } ] } }, { "key" : "INNER_NAME_2_KEY", "data" : { "id" : "OUTER_ID", "name" : "OUTER_NAME", "items" : [ { "id" : "INNER_ID_2", "name" : "INNER_NAME_2" } ] } } ] } 数组中的每个项目,我想在输出的items中创建一个条目,即我想将payload映射到items[i]还可以在输出中创建payload[i].data.itemspayloadkey键,并将datapayload[i].data.id设置为输入的外部payload[i].data.name和{{ 1}}。

可以用jq完成吗?

1 个答案:

答案 0 :(得分:1)

好的,您可以使用以下过滤器:

.id as $id | .name as $name | {payload : [ .items[] | {key:.id, data:{id:$id, name: $name, items:[.]}} ] }

您可以try it here