在python中,如果該元素包含鍵“tags”的值“concept”,我試圖從JSON元素中獲取鍵“relativePaths”的值。JSON 檔案具有以下格式。
]
},
{
"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"
],
我嘗試了以下代碼:
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)
這導致錯誤訊息:
TypeError: argument of type 'int' is not iterable
然后我嘗試了:
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"])
該代碼似乎有效。但是我沒有從 print 命令中得到任何輸出。我究竟做錯了什么?
uj5u.com熱心網友回復:
假設您的 json 是您提出問題的型別串列,您可以像這樣獲得這些值:
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
uj5u.com熱心網友回復:
想通了
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()
uj5u.com熱心網友回復:
我認為這會做你想要的。它更“pythonic”,因為它不使用數字索引來訪問串列的元素——使其更易于撰寫和閱讀)。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426796.html
