jq:id的输出值而不是数字

时间:2015-09-12 03:53:42

标签: json jq

这是我输入的json:

{
    "channels": [
        { "id": 1, "name": "Pop"},
        { "id": 2, "name": "Rock"}
    ],
    "links": [
        { "id": 2, "streams": [ {"url": "http://example.com/rock"} ] },
        { "id": 1, "streams": [ {"url": "http://example.com/pop"} ] }        
    ]
}

这就是我想要的输出:

"http://example.com/pop"
"Pop"
"http://example.com/rock"
"Rock"

所以我需要jq根据.channels[].id

.links[].streams[0].url替换为.links[].id

我不知道它是否正确,但这就是我设法输出网址的方式:

(.channels[].id | tostring) as $ids | [.links[]] | map({(.id | tostring): .streams[0].url}) | add as $urls | $urls[$ids]

"http://example.com/pop"
"http://example.com/rock"

问题是,如何向其中添加.channels[].name

2 个答案:

答案 0 :(得分:0)

你有时必须小心你的要求,但这会产生你想要的结果:

from models import Project
from rest_framework import serializers

class ProjectSerializer(serializers.ModelSerializer):
    """
    Serializes the Project model to send and receive valid JSON data.
    """
    # define a SerializerMethodField
    action = serializers.SerializerMethodField(method_name="get_data_for_action")    

    class Meta:
      model = Project
      fields = ('action', 'title', 'id', 'endDate', 'startDate', 'product')


    def get_data_for_action(self, obj):
        return "createproject" # always add this value in the 'action' key of serialized object representation

给定输入的输出:

.channels[] as $channel
| $channel.name,
  (.links[] | select(.id == $channel.id) | .streams[0].url) 

答案 1 :(得分:0)

以下解决方案使用 reduce setpath $urls创建.links查找表,然后扫描.channels生成相应的网址和名称。

  (
    reduce .links[] as $l (
      {};
      setpath([ $l.id|tostring ]; [$l.streams[].url])
    )
  ) as $urls
| .channels[]
| $urls[ .id|tostring ][], .name

如果“streams”属性中存在多个网址,则会显示 在打印名称之前打印它们。例如如果输入是

{
    "channels": [
        { "id": 1, "name": "Pop"},
        { "id": 2, "name": "Rock"}
    ],
    "links": [
        { "id": 2, "streams": [ {"url": "http://example.com/rock"},
                                {"url": "http://example.com/hardrock"} ] },
        { "id": 1, "streams": [ {"url": "http://example.com/pop"} ] }        
    ]
}

输出将是

"http://example.com/pop"
"Pop"
"http://example.com/rock"
"http://example.com/hardrock"
"Rock"