读取json文件,并使用python打印键值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了读取json文件,并使用python打印键值相关的知识,希望对你有一定的参考价值。
我想要一个应该读取json文件的条件循环,并且打印基于“user_name”的“postId”匹配列表中的项目。
我尝试了这些婴儿步骤,但它没有用
Python版本:2.7.5操作系统:Lenny
这是python脚本:
import sys
import re
import json
my_list = ['windows-super-user','linux user','unix_super_user']
for list_item in my_list:
with open('strings.json') as f:
d = json.load(f)
for userid in d:
if list_item == user_name:
print("Here's the user name :" +user_name+ ", and post id :" +postid)
这是strings.json文件内容;
[
{
"postId":"328e9497740b456154c636349",
"postTimestamp": "1521543600",
"pageType": "/home.php:topnews",
"viewTime": 1521545993647,
"user_name": "windows-super-user",
"gender": 3,
"likes": "8",
"id": "ffa1e07529ac917f6d573a",
"postImg": 1,
"postDesc": [753],
"origLink": 0,
"duration": 0,
"timestamp": 9936471521545,
"back_time": 1521545993693
},
{
"postId":"15545154c636349",
"postTimestamp": "547773600",
"pageType": "/home.php:topnews",
"viewTime": 45993647,
"user_name": "linux user",
"gender": 3,
"likes": "8",
"id": "695e45a17f6d573a",
"postImg": 1,
"postDesc": [953],
"origLink": 0,
"duration": 0,
"timestamp": 545993647,
"back_time": 85993693
},
{
"postId":"9098897740b456154c636349",
"postTimestamp": "899943600",
"pageType": "/home.php:topnews",
"viewTime": 1521545993647,
"user_name": "unix_super_user",
"gender": 3,
"likes": "8",
"id": "917f6d573a695e45affa1e07",
"postImg": 1,
"postDesc": [253],
"origLink": 0,
"duration": 0,
"timestamp": 193647,
"back_time": 1521545993693
},
]
预期产量:
这是用户名:windows-super-user和post id:328e9497740b456154c636349 这是用户名:linux user和post id:15545154c636349 这是用户名:unix_super_user和post id:9098897740b456154c636349
答案
尝试迭代这样:
import sys
import re
import json
my_list = ['windows-super-user','linux user','unix_super_user']
with open('strings.json') as f:
d = json.load(f)
for elem in d:
if elem["user_name"] in my_list:
print("Here's the user name :" +elem["user_name"]+ ", and post id :" +elem["postId"])
我打开文件并加载json,就像你一样。但我只打开文件一次并检查与user_name
的匹配。如果找到匹配项,我会打印出名称和帖子ID。
以上是关于读取json文件,并使用python打印键值的主要内容,如果未能解决你的问题,请参考以下文章
我如何打开文件夹中的 json 文件并阅读它们或在 python 中打印它们