从Python中的json fixture获取项目

从Python中的json fixture获取项目,python,json,dictionary,Python,Json,Dictionary,我有这样的json: [ { fields: { username: "andriy", first_name: "", last_name: "", is_active: true, is_superuser: true, is_staff: true, last_login: "2015-03-26T13:20:01.902Z", groups: [ ], user_per

我有这样的json:

[
  {
    fields: {
      username: "andriy",
      first_name: "",
      last_name: "",
      is_active: true,
      is_superuser: true,
      is_staff: true,
      last_login: "2015-03-26T13:20:01.902Z",
      groups: [ ],
      user_permissions: [ ],
      password: "pbkdf2_sha256$12000$YluCbMyidWwL$yH",
      email: "",
      date_joined: "2015-03-26T13:19:23.269Z"
    },
    model: "auth.user",
    pk: 4
  },
并尝试获取项目“username”的值:

import json
from collections import OrderedDict
from django.http import HttpResponse

path = 'management/test.json'
def load_fixture(name):
    r = json.load(open(path,'r+'), object_pairs_hook=OrderedDict)
    dic =  json.dumps(r, indent=2)
    name = dic['fields'][0]['username'] 
    return HttpResponse(name)
或以这种方式:

....
    def load_fixture(name):
    with open(path,'r+') as json_file:
        json_data = json_file.read()
        dic = json.loads(json_data)
        name = dic['fields'][0]['username']

        return HttpResponse(name)

并且总是会出现错误:“字符串索引必须是整数,而不是str”或“列表索引必须是整数,而不是str”(在第二个代码中)。但是为什么呢?它是听写,不是字符串。我在这里和那里读过很多类似的话题,似乎是在向人们提供建议。我的代码怎么了

dic['fields'][0]['username']
应更改为
dic[0]['fields']['username']
。因此,第二个源代码应该是:

def load_fixture(name):
with open(path,'r+') as json_file:
    json_data = json_file.read()
    dic = json.loads(json_data)
    name = dic[0]['fields']['username']

    return HttpResponse(name)

json.dumps
给你一个字符串,而不是dict。另外,你的
fields
键有
json
作为值,你正在访问它的
0th
索引。刚刚试过:name=dic[0]['fields']['username'],它返回“andriy”。谢谢!我已经这样做了,这对我很有效。