使用python解析JSON文件并在某些条件下选择多个值

时间:2016-10-13 04:26:57

标签: python json

我有这个JSON文件。

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication10._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <br />
    <div style="text-align: center">
        <br />
        <input autofocus="autofocus"  id="myinput1" />
        <br />
        <hr />
    </div>

<script type="text/javascript">
    $(document).ready(function () {
        $("#myinput1").on('input', function () {
            if ($(this).val().length >= 8) {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/fillfields",
                    contentType: "application/json; charset=utf-8",
                    data: '{input: "' + $("#myinput1").val() + '"}',
                    dataType: "json"
                });
                $('#myinput1').val("");
            }
        });
    });

    </script>
</asp:Content>

最初,我正在使用一段代码,这些代码将通过并获取审阅者的全名。

using System;
using System.Web.UI;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication10
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        [System.Web.Services.WebMethod]
        public static void fillfields(string input)
        {
            string constr = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
            using (SqlConnection connection = new SqlConnection(constr))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand("TMS_INSERT", connection))
                {
                    command.CommandType = System.Data.CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@EMP_ID", input);
                    command.ExecuteNonQuery();
                }
                connection.Close();
            }
        }
    }
}

将返回{ "reviewers":[ { "user":{ "name":"keyname", "emailAddress":"John@email", "id":3821, "displayName":"John Doe", "active":true, "slug":"jslug", "type":"NORMAL", "link":{ "url":"/users/John", "rel":"self" }, }, "role":"REVIEWER", "approved":true }, { "user":{ "name":"keyname2", "emailAddress":"Harry@email", "id":6306, "displayName":"Harry Smith", "active":true, "slug":"slug2", "link":{ "type":"NORMAL", "url":"/users/Harry", "rel":"self" }, }, "role":"REVIEWER", "approved":false } ], } 。但是,现在我正在努力获取它,以便脚本在用户名称旁边返回(A),如果他们的标记等于true def get_reviewers(json): reviewers = "" for key in json["reviewers"]: reviewers += key["user"]["displayName"] + ", " reviewers = reviewers[:-2] return reviewers

所以例如上面的代码会得到名字,然后看到John的批准标签是真的而Harry的是假的,然后返回"John Doe, Harry Smith"。我只是不确定从哪里开始这样做。有人能指出我正确的方向吗?

这是我到目前为止所尝试的内容,但显然它不能像我希望的那样工作。

"approved"=true

输出"John Doe(A), Harry Smith"

这是我通过pprint输出def get_reviewers(stash_json): reviewers = "" for key in stash_json["reviewers"]: if stash_json["reviewers"][0]["approved"] == true: reviewers += key["user"]["displayName"] + "(A)" + ", " else: reviewers += key["user"]["displayName"] + ", " reviewers = reviewers[:-2] return reviewers 时的输出。

2 个答案:

答案 0 :(得分:2)

你可能想要这样的内容:

def get_reviewers(stash_json):
    reviewers = ""
    for item in stash_json["reviewers"]:
        if item["approved"]:
            reviewers += item["user"]["displayName"] + "(A)" + ", "
        else:
            reviewers += item["user"]["displayName"] + ", "
    reviewers = reviewers[:-2]
    return reviewers

我认为你的一部分困惑来自&#34;评论家&#34;是listdict个元素,每个dict元素都有一个键值approved,但也有一个键&#34; user&#34;哪个值本身是另一个dict

仔细阅读JSON文件,出于调试目的,请使用大量的

print(...)
print(type(...))   # whether something is a dict, list, str, bool etc

from pprint import pprint    # pretty printing
pprint(...)

答案 1 :(得分:0)

这看起来是使用join和列表理解的好地方:

def get_reviewers(stash_json):
   return ", ".join([item['user']['displayName'] + ('(A)' if item['approved'] else '') for item in stash_json['reviewers']])