python - 是否有任何 JSON 标签过滤示例?
问题描述
我有一个 json 文件,我需要列出所有数据的所有“selftext”元素。有什么例子吗?
数据示例
{ "data": [
{
"selftext": "hello there",
"textex": true,
},
解决方案
如果您希望能够从任意级别的任意 json 中找到密钥,则应使用递归:
def findkey(data, key, resul = None):
if resul is None: resul=[] # initialize an empty list for the results
if isinstance(data, list): # walk down into lists
for d in data:
findkey(d, key, resul)
elif isinstance(data, dict): # dict processing
for k,v in data.items():
if (k == key) and isinstance(v, str): # the expected key and a string value?
resul.append(v)
elif isinstance(v, list) or isinstance(v, dict):
findkey(v, key, resul) # recurse if value is a list or a dict
return resul
例子:
>>> data = { "data": [
{
"selftext": "hello there",
"textex": True,
},
]}
>>> findkey(data, 'selftext')
['hello there']
推荐阅读
- perl - 如何在perl脚本中将文件的内容多次附加到一个文件中
- javascript - 如何在javascript中循环直到满足条件并将结果添加到数组中?
- c# - 增量游戏公式问题
- ansible - Ansible:使用集合时找不到模块
- http - Jenkins:使用 Jenkins 请求插件通过 HTTP POST 将文件上传到服务器
- pycharm - 你能修复 Pycharm 中的工具窗口宽度吗?
- aws-lambda - 运行无服务器批处理作业是否有时间限制?
- javascript - 嵌入的 youtube 视频加载但不播放
- c# - 在 CollectionView 上使用 EventToCommandBehavior 在 Xamarin.Forms v4.8.0 中不起作用
- kubernetes - kubes:如何在强制重启之前让 liveness/readiness 重试