【问题标题】:Remove Backslash from JSON string?从 JSON 字符串中删除反斜杠?
【发布时间】:2017-07-19 14:18:30
【问题描述】:

我正在使用 python url 库从空间参考网站获取 json 响应。这是我的代码。我得到 response_read="u'{\'ty​​pe\': \'EPSG\', \'properties\': {\'code\': 102646}}'" 但我需要这个回复以这种形式:"{'type': 'EPSG', 'properties': {'code': 102646}}"。我如何以这种形式实现输出?

headers = {'User-Agent': 'Mozilla/5.0'}
 req = urllib2.Request("http://spatialreference.org/ref/esri/"nad-1983-stateplane-california-vi-fips-0406-feet"/json/", None, headers)
        response = urllib2.urlopen(req)
        response_read = response.read().decode('utf-8')
        result = json.dumps(response_read)  
        epsg_json = json.loads(result)
        epsg_code = epsg_json['properties']['code']
        return epsg_code

【问题讨论】:

    标签: json python-2.7 urllib2 geospatial urllib


    【解决方案1】:

    你需要先使用转储然后加载

    json_data = json.dumps(response_read)
    json_without_slash = json.loads(json_data)
    

    【讨论】:

      【解决方案2】:

      我不太确定你是否是一个函数。无论如何,您收到的响应是文字字符 ',您需要将其替换为 "。

      这是工作代码:

      import urllib2,json
      headers = {'User-Agent': 'Mozilla/5.0'}
      req = urllib2.Request("http://spatialreference.org/ref/esri/nad-1983-stateplane-california-vi-fips-0406-feet/json/", None, headers)
      response = urllib2.urlopen(req)
      response_read = response.read()
      epsg_json = json.loads(response_read.replace("\'", '"'))
      epsg_code = epsg_json['properties']['code']
      print(epsg_code)
      

      希望这会有所帮助。

      【讨论】:

      • 感谢您的回答。实际上我使用替换函数格式做错了。再次感谢您的回答。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      相关资源
      最近更新 更多