skip to Main Content

i have a stupid error that I can’t figure out how to resolve.

I need to execute a simple python command, and I’d like to keep it inline in a bash command.
Basically I ‘m reading a JSON string and I want to retrieve a value, but I cannot write a "for loop".

i’ll simplify:

string="[{ 'url': 'https://www.example.com/1', 'description': 'URL example number 1', 'name': 'test1', 'id': '1' }, { 'url': 'https://www.example.com/2', 'description': 'URL example number 2', 'name': 'test2', 'id': '2' }]"

echo $string | python3 -c "import sys,json; data= json.load(sys.stdin); for item in data: print(item['id']);"

I get the error

File "<string>", line 1
    import sys,json; data= json.load(sys.stdin); for item in data: print(item['id']);
                                                 ^^^
SyntaxError: invalid syntax

I cannot understand what’s wrong, but I found that if "for" is the first command, then it works. so it must be related to indentation, am I right?

thank you

2

Answers


  1. It’s not allowed by the language as explained here.
    Just split the input string on multiple lines, e.g.:

    $ echo '{"foo":"bar"}' | python3 -c '
    import sys,json;
    data=json.load(sys.stdin);
    for item in data:
      print(item)
    '
    foo
    
    Login or Signup to reply.
  2. It is not recommended to write a Python one-liner as commented by others.
    If you still wish to do it, you need to tweak the script not to include colon
    after the for loop:

    string='[{ "url": "https://www.example.com/1", "description": "URL example number 1", "name": "test1", "id": "1" }, { "url": "https://www.example.com/2", "description": "URL example number 2", "name": "test2", "id": "2" }]'
    
    echo "$string" | python3 -c 'import sys,json; data = json.load(sys.stdin); [print(item["id"]) for item in data]'
    

    Output:

    1
    2
    

    Btw json strings must be enclosed by double quotes, not single quoutes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search