LinuxQuestions.org
Help answer threads with 0 replies.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 07-01-2022, 08:34 AM   #1
flukeyLinux
Member
 
Registered: Sep 2012
Location: Ireland
Distribution: Ubuntu redhat, wsl
Posts: 48

Rep: Reputation: Disabled
Parsing json blob with Python


Hello,
I'm having trouble finding much on this on the web. Any help would be massively appreciated.

I have the following json objects:

Code:
{
    "uuid": "gslbservice",
    "name": "toplevelurl.com",
    "groups": [
        {
            "name": "albpool1",
            "members": [
                {
                    "fqdn": "alb1.com",
                    "enabled": true
                }
            ],
        },
        {
            "name": "albpool2",
            "members": [
                {
                    "fqdn": "alb2.com",
                    "enabled": true
                }
            ],
        }
    ]
}
What I am trying to do is loop through all "members" objects (there could be 2,3 or 4) and updated the "enabled" key to "True" if for example the fqdn = "alb2.com."

I can do this with the first object with:
Code:
          route = "enable"
                fqdn = "alb1"
                for member in element['groups']:
                    if args.fqdn in member['members'][0]['fqdn']:
                        if args.route == "enable":
                            parsed['enabled'] = True
I think my problem is this line:
Code:
if args.fqdn in member['members'][0]['fqdn']
-- explicitly the [0].

is there a way to loop through all objects?

thanks in advance

Last edited by flukeyLinux; 07-01-2022 at 08:35 AM.
 
Old 07-01-2022, 09:03 AM   #2
pan64
LQ Addict
 
Registered: Mar 2012
Location: Hungary
Distribution: debian/ubuntu/suse ...
Posts: 21,976

Rep: Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337
yes, you replace that 0 with a loop, like:
Code:
for member in element['groups']:
    for data in member['members']:
        if args.fqdn in data['fqdn']:
            ....
 
1 members found this post helpful.
Old 07-01-2022, 09:37 AM   #3
flukeyLinux
Member
 
Registered: Sep 2012
Location: Ireland
Distribution: Ubuntu redhat, wsl
Posts: 48

Original Poster
Rep: Reputation: Disabled
Smile

Quote:
Originally Posted by pan64 View Post
yes, you replace that 0 with a loop, like:
Code:
for member in element['groups']:
    for data in member['members']:
        if args.fqdn in data['fqdn']:
            ....
Lovely, so simple

thank you.

do you happen to know how to update a json key that is nested?

Code:
parsed['enabled'] = True
works.
But it is added at the wrong level.

Code:
parsed(member['enabled']) = True
Does not work.

this is my last hurdle
 
Old 07-01-2022, 09:41 AM   #4
pan64
LQ Addict
 
Registered: Mar 2012
Location: Hungary
Distribution: debian/ubuntu/suse ...
Posts: 21,976

Rep: Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337Reputation: 7337
Quote:
Originally Posted by flukeyLinux View Post
Lovely, so simple

thank you.

do you happen to know how to update a json key that is nested?

Code:
parsed['enabled'] = True
works.
But it is added at the wrong level.

Code:
parsed(member['enabled']) = True
Does not work.

this is my last hurdle
this is the same as here:
Code:
member['members'][0]['fqdn'] = new_value
(I have no idea what is that parsed
 
Old 07-01-2022, 09:54 AM   #5
flukeyLinux
Member
 
Registered: Sep 2012
Location: Ireland
Distribution: Ubuntu redhat, wsl
Posts: 48

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by pan64 View Post
this is the same as here:
Code:
member['members'][0]['fqdn'] = new_value
(I have no idea what is that parsed
parsed is basically the json data:

Code:
parsed = json.loads(json_data)
This does not work:
Code:
member['members'][0]['fqdn'] = new_value
parsed['members'][0]['enabled'] = False
KeyError: 'members'

messed about with a few variations of that with no joy.
 
1 members found this post helpful.
Old 07-01-2022, 09:59 AM   #6
boughtonp
Senior Member
 
Registered: Feb 2007
Location: UK
Distribution: Debian
Posts: 3,616

Rep: Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555
Quote:
Originally Posted by flukeyLinux View Post
parsed['members'][0]['enabled'] = False
KeyError: 'members'
The error message is clear - there is a key error with 'members' - i.e. there is no key with that name.

This is equally evident from merely reading the JSON snippet in post #1.

 
Old 07-01-2022, 10:03 AM   #7
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,679
Blog Entries: 4

Rep: Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947
Just grab the JSON, decode it, and print the resulting structure.

The correct way to handle JSON is always to first decode it, then manipulate the resulting data structure, then encode it. Treat the JSON conversion process as a "black box." Python, like every other language these days, uses "known good" software to do this. Do not attempt to manipulate the JSON data textually.
 
1 members found this post helpful.
Old 07-01-2022, 10:29 AM   #8
flukeyLinux
Member
 
Registered: Sep 2012
Location: Ireland
Distribution: Ubuntu redhat, wsl
Posts: 48

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by boughtonp View Post
The error message is clear - there is a key error with 'members' - i.e. there is no key with that name.

This is equally evident from merely reading the JSON snippet in post #1.

As you can "clearly" see (just to be as condescending as you ) from my first comment. the json blob contains object = "members".

Hence why I am asking the question...

Last edited by flukeyLinux; 07-01-2022 at 10:53 AM.
 
Old 07-01-2022, 10:30 AM   #9
flukeyLinux
Member
 
Registered: Sep 2012
Location: Ireland
Distribution: Ubuntu redhat, wsl
Posts: 48

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by sundialsvcs View Post
Just grab the JSON, decode it, and print the resulting structure.

The correct way to handle JSON is always to first decode it, then manipulate the resulting data structure, then encode it. Treat the JSON conversion process as a "black box." Python, like every other language these days, uses "known good" software to do this. Do not attempt to manipulate the JSON data textually.
This information is good. I am new enough to python and have not come across decoding the json first. I must look that up. I am more of a bash head and this would be very easy there. But I need to use python as its a lambda.
 
Old 07-01-2022, 10:45 AM   #10
boughtonp
Senior Member
 
Registered: Feb 2007
Location: UK
Distribution: Debian
Posts: 3,616

Rep: Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555
Quote:
Originally Posted by flukeyLinux View Post
...the json blob contains "members".

Hence why I am asking the question...
You need to back-up and learn basic JSON before going any further.

 
Old 07-01-2022, 10:54 AM   #11
flukeyLinux
Member
 
Registered: Sep 2012
Location: Ireland
Distribution: Ubuntu redhat, wsl
Posts: 48

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by boughtonp View Post
You need to back-up and learn basic JSON before going any further.

Good stuff. thanks lad. I had thought this forum was all part of it. good to know though....
 
Old 07-01-2022, 11:10 AM   #12
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,246

Rep: Reputation: 5323Reputation: 5323Reputation: 5323Reputation: 5323Reputation: 5323Reputation: 5323Reputation: 5323Reputation: 5323Reputation: 5323Reputation: 5323Reputation: 5323
Well, first, JSON in your code sample isn't valid. You can see that by pasting it into https://jsonlint.com/ ...

Also, I'm not sure if you know how to iterate through a dictionary. Looping through it in a "for in" loop will get you its keys. Usually you want to call its .keys() (remember, explicit is better than implicit), .values() or .items() method and loop through that, depending on whether you need its keys, values, or both.

Last edited by dugan; 07-01-2022 at 11:26 AM.
 
1 members found this post helpful.
Old 07-02-2022, 02:35 AM   #13
ondoho
LQ Addict
 
Registered: Dec 2013
Posts: 19,872
Blog Entries: 12

Rep: Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053
As a side remark I want to add that in Linux-speak "blob" means an opaque piece of data (a file), something you cannot (easily) read, e.g. a binary closed source blob, some firmware etc.

JSON is not that.
It is a simple text format, you can look at it in a text editor etc.

There's no need to "decode" it, just format it nicely.
What python does, it loads it into a structure that makes it easier to work with.
There are other (command line) tools that can do similar things, jq comes to mind.
 
1 members found this post helpful.
Old 07-02-2022, 09:07 AM   #14
ntubski
Senior Member
 
Registered: Nov 2005
Distribution: Debian, Arch
Posts: 3,786

Rep: Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083
Quote:
Originally Posted by flukeyLinux View Post
What I am trying to do is loop through all "members" objects (there could be 2,3 or 4) and updated the "enabled" key to "True" if for example the fqdn = "alb2.com."
This is slightly confusing because it's already "true" in your example input?

Quote:
Originally Posted by flukeyLinux View Post
parsed is basically the json data:

Code:
parsed = json.loads(json_data)
Assuming element is somehow a subpart of parsed, I'm guessing you want

Code:
for member in element['groups']:
    for data in member['members']:
        if args.fqdn in data['fqdn']: # should this be "=" instead of "in"?
            data['enabled'] = True

Quote:
Originally Posted by flukeyLinux View Post
I am new enough to python and have not come across decoding the json first.
Your parsed = json.loads(json_data) step is decoding.

Quote:
Originally Posted by ondoho View Post
As a side remark I want to add that in Linux-speak "blob" means an opaque piece of data (a file)[...]
There's no need to "decode" it, just format it nicely.
I think sundialscvs is just using non-standard terminology, as usual (in this case, "decode" = "parse", "blob" = "unparsed data").


Quote:
Originally Posted by dugan View Post
Also, I'm not sure if you know how to iterate through a dictionary.
They're iterating over the arrays, not the dictionaries, I think? (I'm assuming that the JSON array gets parsed into a Python array.)
 
1 members found this post helpful.
Old 07-02-2022, 10:17 AM   #15
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,679
Blog Entries: 4

Rep: Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947Reputation: 3947
@ondoho: What I am specifically saying is that you should treat the JSON data "as a blob." Don't try to "format it" – it doesn't need to be pretty – and don't try to write it yourself. Every programming language has encode/decode support for JSON (and other formats), and uses a standard set of binaries to do it. In this way you know that you can do what needs be done – to interchange structured data reliably with another client. You're handed a "blob" and the means to turn it into a data structure; then, to turn a data structure back into another "blob." And, if you do it this way, you can be confident that it will work correctly.
 
  


Reply

Tags
json, json jq, python



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
LXer: Parsing JSON Data in Python LXer Syndicated Linux News 0 06-23-2020 12:25 AM
[SOLVED] Parsing JSON like string in Python Mark_667 Programming 2 11-09-2018 10:40 AM
[SOLVED] Parsing Json with Python slimcharles Programming 6 03-17-2017 09:04 AM
[SOLVED] Parsing Javascript To JSON Using Python 3 cin_ Programming 3 05-18-2015 04:08 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 08:43 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration