Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print specific data from JSON file lists in a line break layout?

Take this example:

    "something": {
        "random": 0,
        "bag": {
            "papers": 0,
            "pencils": 0
        },
        "PAINT": {
            "COLORS": [
                "A WHITE",
                "B MAPLE",
                "B LOTUS",
                "A OLIVE"
            ],
            "CANS": [
                "SOMETHING"
            ] 
    }

Ignore everything and focus on the COLORS list in the PAINT dictionary… I want to print all colors that have the color A before them, as a code. In other words I want to print "A WHITE" and "A OLIVE". Here’s what happens when I do this:

with open("somethings.json", "r") as f:
   data = json.load(f)

print(data["something"]["PAINT"]["COLORS"])

This is the output:

["A WHITE", "B MAPLE", "B LOTUS", "A OLIVE"]

but like I said, I do not want that… I want only A colors to be printed…
I also do not want THIS:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

["A WHITE", "A OLIVE"]

the output that I really want (which is quite specific) is this:

OLIVE
WHITE

With line breaks (optional: AND in alphabetical order) that is the output that I want. So how can I print this output? is it possible without using any ‘for’ loops? This is a very specific question, would appreciate some help. Thanks –

>Solution :

Try this code:

with open("somethings.json", "r") as f:
   data = json.load(f)

a_colors = [color for color in data["something"]["PAINT"]["COLORS"] if color.startswith("A ")]
colors = [a_color.replace("A ", "") for a_color in a_colors]

print(colors)

How it works

  1. Opens and loads the JSON data.
  2. Uses a list comprehension to filter only entries that start with "A ".
    The .startswith() method of a string returns a boolean value, True if the first few characters of the string are, in fact, the characters passed as an argument, and False otherwise.
  3. Uses another list comprehension to get the string without the "A " for each string in the list created in step 2.
    Replaces the "A " with an empty string, which is a hacky way of deleting part of a string using the .replace() method.

It can be done without list comprehensions using a for loop as well

See code below:

with open("somethings.json", "r") as f:
   data = json.load(f)

a_colors = []
for color in data["something"]["PAINT"]["COLORS"]:
    if color.startswith("A "):
        color_without_a = color.replace("A ", "")
        a_colors.append(color_without_a)

print(a_colors)

This solution uses a for loop rather than a list comprehension but is otherwise the same. (If you are confused, see below for a solution which is an exact replica of the list comprehension one but implemented with for loops).

If you are interested, here is a lengthier solution more similar to the list comprehension one, using for loops:

with open("somethings.json", "r") as f:
   data = json.load(f)

a_colors = []

for color in data["something"]["PAINT"]["COLORS"]:
    if color.startswith("A "):
        a_colors.append(color)

colors = []

for a_color in a_colors:
    colors.append(a_color.replace("A ", ""))
    
print(a_colors)

Recommended reading

Other helpful resources

I strongly recommend watching this video as well:


Thank you for reading! Please upvote if you found it helpful!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading