【问题标题】:JSON Key Values returning errors in Python在 Python 中返回错误的 JSON 键值
【发布时间】:2015-02-11 07:42:56
【问题描述】:

我有一个脚本,我希望将其与 NumPy 一起用于在地理数据库中创建一个要素类。发生了一些事情,当我发送我的请求时,我发送到服务器的相关 json 数据与我的响应不同,因此我无法确定我的键值是什么,如果有的话。我最终希望有一个键值并循环遍历嵌套项以用作要素类中的字段。

代码:

import requests
import json
import jsonpickle
import arcpy
import json
import numpy
import requests


fc = "C:\MYLATesting.gdb\MYLA311"
if arcpy.Exists(fc):
  arcpy.Delete_management(fc)

f = open('C:\Users\Administrator\Desktop\myla311.json', 'r')

data = jsonpickle.encode( jsonpickle.decode(f.read()) )

url = "myURL.com"
headers = {'Content-type': 'text/plain', 'Accept': '/'}

r = requests.post(url)

parsed_json = r.json()

sr = arcpy.SpatialReference(4326)

response = requests.post(url, data=data, headers=headers)
f.close()

ndtype = numpy.dtype([
    ('Comment', 'S48')
])

vehicles = []
for item in parsed_json["La311ServiceRequestNotes"]:
    vehicles.append(tuple(item[k] for k in ndtype.names))

narr = numpy.array(vehicles,  ndtype)
arcpy.da.NumPyArrayToFeatureClass(narr, fc, [34.1728677, -118.5389413], sr)


print response.text

JSON 发送到服务器:

   {
        "MetaData": {},
        "RequestSpecificDetail": {
            "ParentSRNumberForLink": ""
        },
        "SRData": {
            "Anonymous": "Y",
            "Assignee": "",
            "CreatedByUserLogin": "",
            "CustomerAccessNumber": "",
            "LADWPAccountNo": "",
            "Language": "English",
            "ListOfLa311GisLayer": {},
            "ListOfLa311ServiceRequestNotes": {
                "La311ServiceRequestNotes": [
                    {
                        "Comment": "hxhdudi",
                        "CommentType": "Feedback",
                        "FeedbackSRType": "Weed Abatement for Pvt Parcels",
                        "IsSrNoAvailable": "N"
                    },
                    {
                        "Comment": "",
                        "CommentType": "External",
                        "CreatedByUser": "",
                        "IsSrNoAvailable": "N"
                    }
                ]
            },
            "LoginUser": "",
            "MobilOS": "Android",
            "NewContactEmail": "",
            "NewContactFirstName": "",
            "NewContactLastName": "",
            "NewContactPhone": "",
            "Owner": "Other",
            "ParentSRNumber": "",
            "Priority": "Normal",
            "SRCommunityPoliceStation": "RAMPART",
            "SRType": "Feedback",
            "ServiceDate": "01/22/2015",
            "Source": "Mobile App",
            "Status": "Open",
            "UpdatedByUserLogin": ""
        }
    }

错误:

 line 37, in <module>
    for item in parsed_json["La311ServiceRequestNotes"]:
KeyError: 'La311ServiceRequestNotes'

仅使用 requests 模块和 JSON 作为数据提交 POST 请求的成功请求输出示例:

{"status":{"code":311,"message":"Service Request Successfully Submited","cause":""},"Response":{"PrimaryRowId":"1-3J1UX","ListOfServiceRequest":{"ServiceRequest":[{"SRNumber":"1-5927721"}]}}}

出于测试目的,我至少希望将输出 SRNumber 写入我的要素类。

【问题讨论】:

  • parsed_json 长什么样子?
  • 您没有在此处发布 任何内容requests.post(url)。您没有传入数据或标题。
  • 您的 parsed_json 变量包含响应 json。您可以在您的问题中发布第一个请求的响应吗?
  • @thiruvenkadam:第一个请求可能不会产生任何合理的结果,因为发送的 POST 正文将是空的。
  • 我希望第一个请求可以提供完整的元数据,而第二个请求更像是过滤掉的响应。如果没有,parsed_json 应该是 response.json() 而不是 r.json(),应该在以后给出

标签: python json numpy


【解决方案1】:

您不需要先选择SRData 字典吗?

parsed_json["SRData"]["La311ServiceRequestNotes"]

parsed_json 是什么?因为它给你一个 KeyError,所以它是一个字典。它的键是什么?

【讨论】:

  • 我看错了,但是将我解析的 json 设置为 parsed_json = ["SRData"]["La311ServiceRequestNotes"] 会抛出 parsed_json = ["SRData"] ["La311ServiceRequestNotes"] TypeError: list indices must be integers, not str'
  • = ['...'] 应该做什么?
  • 那是parsed_json的问题,我一直没能弄清楚关键。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
  • 2013-08-18
  • 2021-05-01
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
相关资源
最近更新 更多