user12865483
user12865483

Reputation:

How can I get specific fields from within fields in a JSON file?

I have a file called test that I create by fetching info with cURL like this:

curl "https://example.com/public?command=getInfo" > test | python -m json.tool > test

and it results in something like this:

{
    "A_B": {
        "Field1": "0.36564104",
        "Field2": "0.00000580",
        "Field3": "0.00000558",
        "Field4": 177,
        "Field5": "0"
    },
    "B_A": {
        "Field1": "19.02374743",
        "Field2": "0.00049000",
        "Field3": "0.00047179",
        "Field4": 253,
        "Field5": "0"
    },
    "A_C": {
        "Field1": "19.02374743",
        "Field2": "0.00049000",
        "Field3": "0.00047179",
        "Field4": 253,
        "Field5": "0"
    }
    ...
}

I need to get from A_B and A_C Field2 and Field5. Therefore I tried using an AWK live editor but so far the best I've managed is

-F "[, ]+" '/A_B/{print $2,$5}'

Which is to say, I haven't made any real progress, and of course, it doesn't work.

My goal is to save into two files called test2 and test3 which would look something like this:

test2:

A_B: 0.00000580
A_C: 0.00049000

test3:

A_B: 0
A_C: 0

containing the values of Field2 in test2 and Field5 in test3, but so far, I'm stuck.

Any help is appreciated!

Upvotes: 0

Views: 1472

Answers (1)

Freddy
Freddy

Reputation: 4688

Using jq:

jq -r '"A_B: \(.A_B["Field2"])", "A_C: \(.A_C["Field2"])"' test > test2

Explanation: Command

jq -r '.A_B["Field2"]' test

extracts the value 0.00000580 of Field2 of A_B and "A_B: \(…)" adds the literal string A_B: as prefix. The same happens with the A_C field which is printed on the next line. The output is redirected to file test2.

The equivalent command for field5 and output file test3 is

jq -r '"A_B: \(.A_B["Field5"])", "A_C: \(.A_C["Field5"])"' test > test3

Upvotes: 1

Related Questions