Python:JSON无法读取“&”字符

时间:2019-11-20 12:20:19

标签: python json flask encoding

我目前遇到此问题。当我向服务器添加查询时(例如http://127.0.0.1:5000/?property=Ward&propertyValue=Ely%20North%20Ward,其中Ward = Ely North Ward),JSON返回值。但是,如果我想过滤包含“&”字符的病房(例如Ward = Ely&Christchurch Ward),它不会返回任何值,只是 { 类型:“ FeatureCollection”, 特征: [ ] }。

我应该怎么做才能使函数读取“&”字符,并从我输入的内容中返回正确的值?

下面的代码:

from flask import Flask, escape, request 
import requests
import json 



def graphqlwfs(url):
    url = "https://osdatahubapi.os.uk/OSFeaturesAPI/wfs/v1?service=wfs&request=GetCapabilities"
    queryString = "&typenames=osfeatures:BoundaryLine_PollingDistrict&outputformat=geoJSON"


    request_json = request.get_json(silent=True)
    request_args = request.args


    if request_json and 'property' in request_json:
        property = request_json['property']
    elif request_args and 'property' in request_args:
        property = request_args['property']
    else:
        property = ""

    if request_json and 'propertyValue' in request_json:
        propertyValue = request_json['propertyValue']
    elif request_args and 'propertyValue' in request_args:
        propertyValue = request_args['propertyValue']
    else:
        propertyValue = ""


    filterString = "&filter=<Filter><PropertyIsEqualTo><PropertyName>" + str(property) + "</PropertyName><Literal>" + str(propertyValue) + "</Literal></PropertyIsEqualTo></Filter>"

    if property == "":
        filterString = ""
    if propertyValue == "":
        filterString = ""


    newUrl = str(url.replace("GetCapabilities", "GetFeature") + queryString + filterString)
    response = requests.get(newUrl)

    features = response.json()



    return features


        ```







2 个答案:

答案 0 :(得分:0)

尝试转义&字符。在这种情况下,&的代码为%26。因此,您可以尝试

?property=Ward&propertyValue=Ely%20%26%20Christchurch%20Ward

有关更多信息,请阅读this链接。

答案 1 :(得分:-1)

对我来说,它的工作正常,可能是我错了,告诉我将更改答案,可能需要更多描述。

H3