如何将这个unicode转换成dict?

2024-04-30 02:36:37 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,我完全忘了提到我使用的是Python。让我再试一次。在

我使用Python来使用一个返回以下JSON的web服务:

{
  "results" : [
    {
      "paramName" : "output",
      "dataType" : "GPString",
      "value" : "{'city': 'Falls Church', 'isRuralArea': False, 'zip': '22046', 'isNotInBTOPLMArea': True, 'longitude': '-77.186180', 'isGeocodable': True, 'county': u'Falls Church', 'isNotInBIPLMArea': True, 'state': 'VA', 'isLatLongInUSBounds': True, 'address': '604 Jackson St', 'latitude': '38.884937'}"
    }
  ],
  "messages" : [

  ]
}

以下是我的获取/解析代码中的重要片段:

^{pr2}$

不幸的是,这给我留下了以下results的值(正如PyScripter调试器的Variables窗口中报告的那样):

u"{'city': 'Falls Church', 'isRuralArea': False, 'zip': '22046', 'isNotInBTOPLMArea': True, 'longitude': '-77.186180', 'isGeocodable': True, 'county': u'Falls Church', 'isNotInBIPLMArea': True, 'state': 'VA', 'isLatLongInUSBounds': True, 'address': '604 Jackson St', 'latitude': '38.884937'}"

例如,我不知道如何访问地址城市键。在

你能告诉我我做错了什么吗,以及如何解决它吗?在

谢谢, 杰米


我的问题的旧版本(过时):

下面是我正在解析的JSON:

response = {u'messages': [], u'results': [{u'dataType': u'GPString', u'value': u"{'city': 'Falls Church', 'isRuralArea': False, 'zip': '22046', 'isNotInBTOPLMArea': True, 'longitude': '-77.186180', 'isGeocodable': True, 'county': u'Falls Church', 'isNotInBIPLMArea': True, 'state': 'VA', 'isLatLongInUSBounds': True, 'address': '604 Jackson St', 'latitude': '38.884937'}", u'paramName': u'output'}]}

我已经深入到这个节点,它的类型是“unicode”。我如何从中得出dict?我认为unicode的事实阻止了我创建dict或访问它的键,但我不确定。在

u"{'city': 'Falls Church', 'isRuralArea': False, 'zip': '22046', 'isNotInBTOPLMArea': True, 'longitude': '-77.186180', 'isGeocodable': True, 'county': u'Falls Church', 'isNotInBIPLMArea': True, 'state': 'VA', 'isLatLongInUSBounds': True, 'address': '604 Jackson St', 'latitude': '38.884937'}"

谢谢, 杰米


Tags: falsetruecityzipchurchstatecountyva
2条回答

由于您的results对象看起来像dict的string/unicode版本,因此需要对其求值。一种安全的方法(从Python 2.6开始)是使用ast.literal_eval函数:

results = ast.literal_eval(responseAsJson['results'][0]['value'])

这几乎不是一个完整的答案,因为很难说出你想要什么。但首先要纠正JSON字符串。在

以下是您可能需要的JSON格式:

{'messages': [], 'results': [{'dataType': 'GPString', 'value': {'city': 'Falls Church', 'isRuralArea': False, 'zip': '22046', 'isNotInBTOPLMArea': True, 'longitude': '-77.186180', 'isGeocodable': True, 'county': 'Falls Church', 'isNotInBIPLMArea': True, 'state': 'VA', 'isLatLongInUSBounds': True, 'address': '604 Jackson St', 'latitude': '38.884937'}, 'paramName': 'output'}]}

我删除了几个属性名前面的u,并从第一个名为'value'的属性中删除了周围的{}。在

现在,关于你最初的问题,我们需要更多的细节。请发布您的代码和您使用的语言/平台?根据您评论中提到的responseAsJson()猜测,您是否使用RadAjax来ASP.NET?http://www.telerik.com/help/aspnet/ajax/ajxsimplewebserviceinvocation.html

不要在这里回复,而是编辑到你的帖子中。在

相关问题 更多 >