3

I've searched across dozens of answers for the last week but I haven't been able to find an example of what I'm trying to do, happy to be pointed to something that I've missed, and I'm new to Python so I apologise if this is something trivial.

I'm trying to read in a configuration from a JSON file so that I can abstract the configuration from the script itself.

I want to be able to assign the configuration value to a variable and perform an action on it, before moving on to the next category in a nested list, of which the categories could change/expand over time (music, pictures, etc).

The JSON file (library.json) currently looks like this:

{"media":{
    "tv": [{
        "source": "/tmp/tv",
        "dest": "/tmp/dest"
        }],
    "movies": [{
        "source": "/tmp/movies",
        "dest": "/tmp/dest"
    }]
}}

The relevant script looks like this:

import json
with open(libfile) as data_file:
data = json.load(data_file)

for k, v in (data['media']['tv']):
    print (k, v)

What I was hoping to see as output was:

dest /tmp/dest
source /tmp/tv 

What I am seeing is:

dest source

It feels like I'm missing something simple.

1
  • Apologies in advance, my upvotes don't count because I am too much of a newbie. Commented Dec 3, 2018 at 2:00

3 Answers 3

2

This works,

import json
with open('data.json') as json_file:
  data = json.load(json_file)
  for p in data['media']['tv']:
      dst = (p['dest'])
      src = (p['source'])
      print (src, dst)
Sign up to request clarification or add additional context in comments.

2 Comments

Please add more explanation, telling how this would solve the problem and what approach you followed.
@glen-kennedy I have detailed the answer and make it precise, so there are no confusions
0

Something like this? Using f-strings and zip() that will aggregate elements.

import json
with open("dummy.json") as data_file:
    data = json.load(data_file)

for i, j in data["media"].items():
    print(i)
    print("\n".join(f'{str(k)} {str(l)}' for k,l in list(zip(j[0].keys(), j[0].values()))))
    print("\n")

Output:

tv
source /tmp/tv
dest /tmp/dest


movies
source /tmp/movies
dest /tmp/dest

2 Comments

I assume I'm making a transcription mistake, but I am getting a syntax error on execution with this code: with open(libfile) as data_file: data = json.load(data_file) for i, j in data["media"].items(): print(i) print("\n".join(f'{str(k)} {str(l)}' for k,l in list(zip(j[0].keys(), j[0].values())))) print("\n")
That would be it then, I am running 3.5.
0

The problem here is that data['media']['tv'] is actually a list of dictionaries.

You can tell because it looks like this: "movies": [{.. (Note the bracket [)

That means that instead of this:

for k, v in (data['media']['tv']):
    print (k, v)

You should be doing this:

for dct in (data['media']['tv']):
    for k, v in dct.items():
        print(k, v)

1 Comment

This also worked, which is confusing the crap out of me, because I am sure I tried this before and it threw up errors, but I think I had the items() in the wrong place previously. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.