0

I’m starting from this structure:

[{
    "experiment": "ex1",
    "models": [{
        "name": "model1",
        "reference": 0.1,
        "code": [{
            "name": "foo",
            "version": "a",
            "value": 0.2
        },{
            "name": "foo",
            "version": "b",
            "value": 0.2
        },{
            "name": "bar",
            "version": "a",
            "value": 0.15
        }]
    },{
        "name": "model2",
        "reference": 0.12,
        "code": [{
            "name": "foo",
            "version": "a",
            "value": 0.09
        },{
            "name": "baz",
            "version": "a",
            "value": 0.15
        }]
    }]
}]

and I want this as the result:

{
  "model": "model1",
  "code": "foo",
  "version": "a"
}
{
  "model": "model1",
  "code": "foo",
  "version": "b"
}
{
  "model": "model1",
  "code": "bar",
  "version": "a"
}
{
  "model": "model2",
  "code": "foo",
  "version": "a"
}
{
  "model": "model2",
  "code": "baz",
  "version": "a"
}

So I wrote the following query.

.[] | { "model": .name, "code": .code[].name, "version": .code[].version }

The problem is that for each use of .code[] in the output structure the results are multiplied, resulting in many duplicates. How can I avoid that, and get only the desired result?

1 Answer 1

2

Many similar questions have been asked before[1][2][3][4].... You need to avoid expanding the same array more than once as shown below to prevent a combinatorial explosion.

.[].models[] | {model: .name} + (.code[] | {name, version})

Online demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.