-2

I am trying to extract some particular data from the JSON so i wrote the following code

echo "$Group_ID" | python -c 'import json,sys;obj=json.load(sys.stdin); for o in obj: if o[name] == "Admin_UserGroup": print o["id"]';

But its throwing error

Can someone please help and tell me what wrong with the code?

   File "<string>", line 1
     import json,sys;obj=json.load(sys.stdin); for o in obj: if o["name"] == "Admin_UserGroup": print o["id"]
                                                 ^
SyntaxError: invalid syntax

Here is the version details

[root@mdfdevha1 ~]# python -V
Python 2.7.5

EDIT 1 : Attaching the image

enter image description here

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
  • Do you use Python 2? – Martin Thoma Aug 01 '18 at 06:51
  • Did you try executing it as a normal script (not on a single line)? – Martin Thoma Aug 01 '18 at 06:52
  • @MartinThoma I updated version information and yes i am trying it in single line . – Subodh Joshi Aug 01 '18 at 06:54
  • @U9-Forward In this example https://www.w3schools.com/python/python_for_loops.asp they wrote same. – Subodh Joshi Aug 01 '18 at 06:57
  • @AdamSmith Sorry, i was wrong, from the one line of whole code is confusing me – U13-Forward Aug 01 '18 at 06:58
  • @SubodhJoshi I am suggesting to use multiple lines. I don't see a point in having it in a single line... – Martin Thoma Aug 01 '18 at 07:03
  • I've attempted to edit your post to match the picture you posted below. You improperly copied the code *and* didn't give us all the info in the error traceback. The solution is to write a python script, not to one-line it. – Adam Smith Aug 01 '18 at 07:06
  • As noted in the linked dupe and [also this closely-related question](https://stackoverflow.com/questions/26778181/for-loop-after-import-doesnt-work-in-python-one-liner), what your trying to do cannot be done in a one-liner. As many many many have told you already: write a script. – Adam Smith Aug 01 '18 at 07:14
  • @KGS Your multiple line code worked but i dont want to print none. – Subodh Joshi Aug 01 '18 at 07:18
  • @SubodhJoshi your own code will work when you write it as a script. The only problem here is attempting to separate simple and compound statements with a semicolon, which is not accepted in the Python grammar. – Adam Smith Aug 01 '18 at 07:19
  • @AdamSmith Thanks can you please tell how to avoid the print none? – Subodh Joshi Aug 01 '18 at 07:20
  • @SubodhJoshi Use your own code! It doesn't print `None`. I don't know why KGSH was trying to get you to use that ternary idiom `if pred then a else b`. It's not useful for the task at hand. – Adam Smith Aug 01 '18 at 07:22
  • 1
    @AdamSmith Ok i will see the feasibility for my requirement to write python code in a file. – Subodh Joshi Aug 01 '18 at 07:23
  • @SubodhJoshi I have found a way to do it in one line - Please read my answer – Gareth Ma Aug 01 '18 at 07:25

2 Answers2

2

First, you should also post the Error - 'Syntax Error'

Also, this will be helpful: One-line list comprehension: if-else variants

Therefore, this python code should work for you:

import json ,sys;
obj = json.load(sys.stdin);
print ('\n'.join([str(o["id"]) if o[name] == "Admin_UserGroup" else "" for i in obj]).replace('\n\n','\n').strip('\n'))

Shrink it into a one liner:

echo "$Group_ID" | python -c "import json,sys;obj=json.load(sys.stdin);print ('\n'.join([str(o['id']) if o[name] == 'Admin_UserGroup' else '' for i in obj]).replace('\n\n','\n').strip('\n'))";

EDIT: After 10 minutes of bug fixing, this works!
Let's print the even numbers in 1 - 10:

print('\n'.join([str(i) if i % 2 == 0 else '' for i in range(1, 11)]).replace('\n\n','\n').strip('\n'))

Which outputs as expected

EDIT 2: you cannot use single quotes in your python command

Edit 3: Working command

[root@mdfdevha1 ~]# echo "$Group_ID" | python -c "import json,sys;obj=json.load(sys.stdin);print ('\n'.join([str(i['id']) if i['name'] == 'Admin_UserGroup' else '' for i in obj]).replace('\n\n','\n').strip('\n' ))";
Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
Gareth Ma
  • 329
  • 2
  • 11
  • I'm not sure how this is different. – Adam Smith Aug 01 '18 at 07:07
  • It's different because it works – Gareth Ma Aug 01 '18 at 07:07
  • @KGSHbteamMineTeamBeastO_ If whole command in one line its a issue in Python ,as i dont know python . – Subodh Joshi Aug 01 '18 at 07:08
  • Since the code is throwing an error on the `for` loop (even with your code) I beg to differ. – Adam Smith Aug 01 '18 at 07:08
  • There's no reason to use the `if pred then a else b` idiom here. Note that `print number` is also equal `None` (with a side effect). Just `if number % 2: print number` is fine -- it just doesn't work in this context (after an import statement and a semicolon in a one-line expression) – Adam Smith Aug 01 '18 at 07:13
  • Yep - I just tried to make it work in 1 line – Gareth Ma Aug 01 '18 at 07:14
  • @KGSHbteamMineTeamBeastO_ right, I understand, but if you'd tested it you'd have realized it still doesn't work.... – Adam Smith Aug 01 '18 at 07:16
  • All problems fixed – Gareth Ma Aug 01 '18 at 07:24
  • @KGSHbteamMineTeamBeastO_ For your online command giving `Traceback (most recent call last): File "", line 1, in NameError: name 'n' is not defined` – Subodh Joshi Aug 01 '18 at 07:28
  • @SubodhJoshi I can't seem to reproduce your error – Gareth Ma Aug 01 '18 at 07:30
  • @KGSHbteamMineTeamBeastO_ one issue is object name will be `i` in place of `o` second after making this change its saying `Traceback (most recent call last): File "", line 1, in NameError: name 'name' is not defined` then i added `""` in name that also not worked But after adding single quotes its worked. – Subodh Joshi Aug 01 '18 at 07:33
  • Double quotes don't work because your `python -c ..` is bracketed with double quotes, and if you use it in your python script it will 'crash' – Gareth Ma Aug 01 '18 at 07:35
  • @KGSHbteamMineTeamBeastO_ I updated your answer with working command Thanks for your help. – Subodh Joshi Aug 01 '18 at 07:36
0

The key of a JSON should be given within quotes.

Try this:

echo "$Group_ID" | python -c 'import json,sys;obj=json.load(sys.stdin); for o in obj: if o["name"] == "Admin_UserGroup": print o["id"]'

Thanks

Gareth Ma
  • 329
  • 2
  • 11
SanthoshSolomon
  • 1,383
  • 1
  • 14
  • 25