我无法正确解析JSON字符串。似乎无法使用JSON.parse。 eval成功了,但我想要安全的方式:) 我以这种方式在aspx Service类中查询网站:
[OperationContract]
public String queryNominatim(String request)
{
string uri = "http://nominatim.openstreetmap.org/search.php?q=" + request + nominatimParams;
string response = "from ajax";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
req.UserAgent = HttpContext.Current.Request.UserAgent;
req.Method = "POST";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Encoding enc = Encoding.GetEncoding(resp.CharacterSet);
StreamReader reader = new StreamReader(resp.GetResponseStream(), enc);
response = reader.ReadToEnd();
reader.Close();
return response;
}
请求是街道名称,如“windmühlenstraße”。 完整的uri是“http://nominatim.openstreetmap.org/search.php?q =windmühlenstraße& format = json& countrycodes = de& addressdetails = 1”
答案是一个JSON字符串,我只想传递给调用的javascript代码。 http://jsonlint.com/验证这是正确的。
但是在javascript中,这段代码
arr = JSON.Parse(response);
抛出异常:
TypeError:JSON.Parse不是函数
这是我到目前为止所发现的:
JSON.Parse
已存在且正在运作。我在javascript中尝试了另一个json-string硬编码。arr = eval("(" + response + ")");
按预期工作。数组和对象是完全可访问的。我将转义的unicode chars服务器端转换为unicode字符:
private string DecodeEncodedNonAsciiCharacters(string value)
{
return Regex.Replace(
value,
@"\\u(?<Value>[a-zA-Z0-9]{4})",
m =>
{
return ((char)int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString();
});
}
但无论如何都会抛出异常。
var original = "[{\"place_id\":\"2413006\",\"licence\":\"Data \u00a9 OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap.org\/copyright\",\"osm_type\":\"node\",\"osm_id\":\"344446896\",\"boundingbox\":[\"52.3739283\",\"52.3740283\",\"9.7434778\",\"9.7435778\"],\"lat\":\"52.3739783\",\"lon\":\"9.7435278\",\"display_name\":\"6, Theaterstra\u00dfe, Mitte, Hannover, Region Hannover, Niedersachsen, 30159, Deutschland\",\"class\":\"place\",\"type\":\"house\",\"importance\":0.311,\"address\":{\"house_number\":\"6\",\"road\":\"Theaterstra\u00dfe\",\"suburb\":\"Mitte\",\"city_district\":\"Mitte\",\"city\":\"Hannover\",\"county\":\"Region Hannover\",\"state\":\"Niedersachsen\",\"postcode\":\"30159\",\"country\":\"Deutschland\",\"country_code\":\"de\"}}]";
jsObject = JSON.parse(original);
alert(jsObject[0] + ": " + jsObject[0].display_name);
这是成功的。显示了displayname。
在json字符串中转换和excaped unicode没有区别。 Firefox显示正确的字母。
在chrome中错误拼写错误:typeerror:undefined不是函数。 IE:typeerror:dasobjektunterstütztdieEigenschaft oder Methode“parse”nicht。含义:对象不支持属性或方法“解析”。
有什么不对?复制和粘贴转换是什么,我想念? 我错过了什么?
答案 0 :(得分:1)
JSON.Parse
,您需要JSON.parse
。小写 p !
答案 1 :(得分:1)
从我的第一个代码段arr = JSON.Parse(response);
可以看出,您正在尝试使用JSON.parse
的大写版本。在所有现代浏览器中,第二个代码段对我来说都很合适。请参阅文档here。 JavaScript区分大小写。