读取json文件,并使用python

时间:2019-04-26 01:16:40

标签: python json key

我想要一个条件循环,该循环应读取json文件,并根据“ user_name”打印“ postId”与列表中的项目匹配。

我尝试了这些婴儿步骤,但是没有用

Python版本:2.7.5 操作系统:Linux

这是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,发布ID:328e9497740b456154c636349
  用户名:linux user,发布ID:15545154c636349
  这是用户名:unix_super_user,发布ID:9098897740b456154c636349

1 个答案:

答案 0 :(得分:1)

尝试这样迭代:

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。