Home > Software design >  Access nested json file values
Access nested json file values

Time:03-13

My .json file contains:

"message": [
    {
        "first": [
            "hi",
            "hii"
        ],
        "second": [
            "bye",
            "byee"
        ]
    }
]

I want Python to randomly print hi or hii and bye or byee, choice would fit here.

But to use it I firstly need to print the values of first and second.

My code only prints

first
second

Here it is:

def read_settings(file):
    with open(file, encoding = 'utf-8') as f:
        return load(f)

# Read json file
file = read_settings('settings.json')

for i in file['message'][0]:
    print(i)

I want it to print

hi # or hii
bye # or byee

CodePudding user response:

Try using random module with a list comprehension:

random.choice([x for y in myFile["message"][0] for x in myFile["message"][0][y]])

Note that, I have changed the variable you named file into myFile because file is kind of predefined in python.

This function returns a random element of the list ["hi", "hii", "bye", "bye"]. But if you want to return value of first key or second key, you can try:

random.choice([myFile["message"][0][x] for x in myFile["message"][0]])

This one, actually returns a list. It returns ['hi', 'hii'] or ['bye', 'byee']

CodePudding user response:

When you iterate through an dictionary like you have (for i in file['message'][0]:), it only fetch the keys of that dictionary. To print the random values wrt the key try using:

import random
for key, values in file['message'][0].items():
    print(random.choice(values))

CodePudding user response:

Your code snippet

for i in file['message'][0]:
    print(i)

Just prints the key of the python dictionary:

{'first': ['hi', 'hii'], 'second': ['bye', 'byee']}

In order to get values and hence the desired output just modify your code to import random library

import random

...
...
...

for i in file['message'][0]:
    values = file['message'][0][i]
    random.choices(values)

CodePudding user response:

import random
for option in file['message']:
  for value in option.keys():
    print(option[value][random.randrange(0,2)])

for option in file['message'] -> return 'first' and 'seccond' with its values inside ("hi", "hii" and "bye", "byee")

for value in option.keys(): -> pick just 'first' and 'second' values

print(option[value][random.randrange(0,2)]) -> select the "hi" or "hii", (option[0][0] will be "hi"), so select option[0][random value between 0 and 1].

That way you have your values generated randomly.

  • Related