'Getting value from a JSON file based on condition

In python I'm trying to get the value(s) of the key "relativePaths" from a JSON element if that element contains the value "concept" for the key "tags". The JSON file has the following format.

    ]
  },
  {
    "fileName": "@Weizman.2011",
    "relativePath": "Text/@Weizman.2011.md",
    "tags": [
      "text",
      "concept"
    ],
    "frontmatter": {
      "authors": "Weizman",
      "year": 2011,
      "position": {
        "start": {
          "line": 0,
          "col": 0,
          "offset": 0
        },
        "end": {
          "line": 4,
          "col": 3,
          "offset": 120
        }
      }
    },
    "aliases": [
      "The least of all possible evils - humanitarian violence from Arendt to Gaza"
    ],

I have tried the following codes:

import json
with open("/Users/metadata.json") as jsonFile:
 data = json.load(jsonFile)
 for s in range(len(data)):
  if 'tags' in s in range(len(data)):
   if data[s]["tags"] == "concept":
    files = data[s]["relativePaths"]
    print(files)

Which results in the error message:

TypeError: argument of type 'int' is not iterable

I then tried:

with open("/Users/metadata.json") as jsonFile:
 data = json.load(jsonFile)
 for s in str(data):
  if 'tags' in s in str(data):
    print(s["relativePaths"])

That code seems to work. But I don't get any output from the print command. What am I doing wrong?



Solution 1:[1]

Figured it

import json


f = open("/Users/metadata.json")
# returns JSON object as
# a dictionary
data = json.load(f)
 
# Iterating through the json
# list
for i in data:
    if "tags" in i:
     if "concept" in i["tags"]:
      print(i["relativePaths"])
 
# Closing file
f.close()

Solution 2:[2]

I think this will do what you want. It is more "pythonic" because it doesn't use numerical indices to access elements of the list — making it easier to write and read).

import json

with open("metadata.json") as jsonFile:
    data = json.load(jsonFile)
    for elem in data:
        if 'tags' in elem and 'concept' in elem['tags']:
            files = elem["relativePath"]
            print(files)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aiivu
Solution 2 martineau