Home > Enterprise >  Getting value from a JSON file based on condition
Getting value from a JSON file based on condition

Time:02-18

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?

CodePudding user response:

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

CodePudding user response:

Assuming your json is a list of the type you put on your question, you can get those values like this:

with open("/Users/metadata.json") as jsonFile:
    data = json.load(jsonFile)
    for item in data:  # Assumes the first level of the json is a list
        if ('tags' in item) and ('concept' in item['tags']): # Assumes that not all items have a 'tags' entry
            print(item['relativePaths'])  # Will trigger an error if relativePaths is not in the dictionary

CodePudding user response:

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)
  • Related