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

Time:04-08

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:

["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 -

CodePudding user response:

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(colors)

To sort alphabetically, use the sorted() function, like this for the list comprehension solution and the second for loop solution:

sorted_list = sorted(colors)
print(sorted_list)

For the first for loop solution:

sorted_list = sorted(a_colors)
print(sorted_list)

Recommended reading

Other helpful resources

I strongly recommend watching this video as well:


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

CodePudding user response:

Well, you can't really don't use a for-loop, you need to iterate over all elements in your COLORS array. So, what you want to do is:

  1. Iterate over all elements
  2. Check if the first character of each element (e.g. A WHITE) is the desired character (e.g. A)
  3. either print the output directly or store it in list without the A (notice the space)

So:

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

colors = data["something"]["PAINT"]["COLORS"]
best_colors = []

for color in colors:
  if color[0] == "A": # or any character you want; CASE SENSITIVE!
    best_colors.append(color[2:]) # this adds the color without the A and the space to the list

# Optionally: Sort alphabetically
sorted_colors = sorted(best_colors)

Additional resources to help you to understand the code better:

CodePudding user response:

Based on Unix Doughnut's answer:

# Read JSON File
with open("file_name.json", "r") as f: 
    data = json.load(f)

# Sort the selected elements starting with A without the leading A
colors = sorted([color.replace("A ", "") for color in data["something"]["PAINT"]["COLORS"] if color.startswith("A ")])

# Print list elements separated by line break ( without for loop )
print(*colors, sep='\n')`
  • Related