1

When I use:

for reports in raw_data:
        for names in reports["names"]:
                report_name = json.dumps(names).strip('"')
                report_names.append(report_name)

I get the key/object name: 'report1', ...

When I use:

for reports in raw_data:
        for names in reports["names"].values():
                report_name = json.dumps(names).strip('"')
                report_names.append(report_name)

I get the value of the object: 'name1', ...

How do get the object and value together, for example: 'report1': 'name1', ...

The json:

[
  {
    "names": {
      "report1": "name1",
      "report2": "name2"
    }
  },
  {
    "names": {
      "report3": "name3",
      "report4": "name4"
    }
  }
]

2 Answers 2

1

You need to loop over each dictionary in the object, then extract each key: value pair from items():

data = [
  {
    "names": {
      "report1": "name1",
      "report2": "name2"
    }
  },
  {
    "names": {
      "report3": "name3",
      "report4": "name4"
    }
  }
]

for d in data:
    for k, v in d["names"].items():
        print(k, v)

Result:

report1 name1
report2 name2
report3 name3
report4 name4

Or if you can just print out the tuple pairs:

for d in data:
    for pair in d["names"].items():
        print(pair)

# ('report1', 'name1')
# ('report2', 'name2')
# ('report3', 'name3')
# ('report4', 'name4')

If you want all of the pairs in a list, use a list comprehension:

[pair for d in data for pair in d["names"].items()]
# [('report1', 'name1'), ('report2', 'name2'), ('report3', 'name3'), ('report4', 'name4')]
Sign up to request clarification or add additional context in comments.

Comments

0

Try something like this:

import json
with open(r'jsonfile.json', 'r') as f:
        qe = json.load(f)
        for item in qe:
            if item == 'name1': 
                print(qe)

Comments

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.