Home > Enterprise >  How to access, parse and print json data with square brackets with command line?
How to access, parse and print json data with square brackets with command line?

Time:10-15

The following command line is executed:

`curl ..... | python -m json.tool`

produces the following output (note the square branckets []):

[
     { "test" : "a"
     },
     { "test" : "b"
     },
     { "test" : "c"
     },
     { "test" : "d"
     },
     { "test" : "e"
     }
]

We tried

curl ..... | python -m json.tool | python -c 'import json,sys; obj=json.load(sys.stdin); print obj[0]["test"];

It gives output

a

Q1) how do we access and print all elements to give an output like this below ?

a
b  
c
d
e

Q2) how do we access and print a range of specified elements, say 1st to 3rd elements to give an output like this below ?

b  
c
d

Thank you

CodePudding user response:

not sure if I got this right,

  1. To access and print all elements, you can use a for loop:

    for element in obj: print(element["test"])

  2. To access and print a range of elements, you can use a for loop with a range:

    for i in range(1,4): print(obj[i]["test"])

CodePudding user response:

For Q1,

curl ..... | python -m json.tool | python -c 'import json,sys
obj=json.load(sys.stdin)
li=[x["test"] for x in obj]
print("\n".join(li));'

For Q2,

curl ..... | python -m json.tool | python -c 'import json,sys
obj=json.load(sys.stdin)
li=[x["test"] for x in obj]
print("\n".join(li[1:4]));'
  • Related