I'm working to parse some content from a curl command to an API which returns JSON. this will return an array of data with a variable number of records in an array, but always 1 or more. here's some example data:
{
"item_count": 1,
"items": [
{
"id": 3315226,
"name": "jason",
"type": "AA"
}
]
}
I need to count the number of items in the ["items"] array, or use "item_count", and loop over each one in a for loop to grab the "id" value. I formulated the following:
curl -s -k -u ...... http://api | python -c 'import sys,json; obj=json.load(sys.stdin); for i in range(1, obj["item_count"]): print obj["items"][i]["id"]'
...which seems like it should work to me, but i end up with an error on the 'r' of 'for':
import sys,json; obj=json.load(sys.stdin); for i in range(1, obj["item_count"]): print obj["items"][i]["id"]
^
SyntaxError: invalid syntax
I went hell and high water trying to reformulate the for statement and the data it was fed, but eventually got back to basics and found that the 'import json' portion was killing my for statement. The following works:
python -c 'for i in range(0, 6): print i'
The following does not:
python -c 'import json; for i in range(0, 6): print i'
So my question to you is, how should I use a for loop while also importing the json module?
EDIT:
The solution here seems to be not to try and put complex python into a one liner. In this case, however, since I only needed to print something, a future call to turn 'print' into a function instead a builtin helped. My final working string:
curl -s -k -u ...... http://api | python -c 'from __future__ import print_function; import sys,json; obj=json.load(sys.stdin); [print (obj["items"][i]["id"])for i in range(obj["item_count"])]'