最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

.net - Native javascript JSON.parse throws typeError - Stack Overflow

programmeradmin1浏览0评论

I'm stuck parsing a JSON string correctly. There seems no way to use JSON.parse. eval succeeds, but I want the secure way :) I query a website in an aspx Service class this way:

        [OperationContract]
    public String queryNominatim(String request)
    {
        string uri = ".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;
    }

Where request is a street name like "windmühlenstraße". The full uri is ".php?q=windmühlenstraße&format=json&countrycodes=de&addressdetails=1"

The answer is a JSON string which i just want to deliver to the calling javascript code. / validates that as correct.

But in javascript, this code

arr = JSON.Parse(response);

throws an Exception:

TypeError: JSON.Parse is not a function

This is what I found out so far:

  1. JSON.Parse is existing and working. I tried another json-string hard-coded in javascript successfully.
  2. arr = eval("(" + response + ")"); works as expected. The array and objects are fully accessable.
  3. I converted the escaped unicode chars serverside to unicode chars by this:

    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();
            });
    }
    

    But the exception is thrown anyway.

  4. I hardcoded copy&pasted answeres to to Javascript:
var original = "[{\"place_id\":\"2413006\",\"licence\":\"Data \u00a9 OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap\/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);

which is successfull. displayname is shown.

converted and excaped unicode in json string makes no difference. Firefox displays correct letters.

in chrome the error is spelled: typeerror: undefined is not a function. IE: typeerror: das objekt unterstützt die Eigenschaft oder Methode "parse" nicht. Meaning: Object doesn't support property or method "parse".

what is wrong? Is the copy&paste converting something, i miss? What am I missing???

I'm stuck parsing a JSON string correctly. There seems no way to use JSON.parse. eval succeeds, but I want the secure way :) I query a website in an aspx Service class this way:

        [OperationContract]
    public String queryNominatim(String request)
    {
        string uri = "http://nominatim.openstreetmap/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;
    }

Where request is a street name like "windmühlenstraße". The full uri is "http://nominatim.openstreetmap/search.php?q=windmühlenstraße&format=json&countrycodes=de&addressdetails=1"

The answer is a JSON string which i just want to deliver to the calling javascript code. http://jsonlint./ validates that as correct.

But in javascript, this code

arr = JSON.Parse(response);

throws an Exception:

TypeError: JSON.Parse is not a function

This is what I found out so far:

  1. JSON.Parse is existing and working. I tried another json-string hard-coded in javascript successfully.
  2. arr = eval("(" + response + ")"); works as expected. The array and objects are fully accessable.
  3. I converted the escaped unicode chars serverside to unicode chars by this:

    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();
            });
    }
    

    But the exception is thrown anyway.

  4. I hardcoded copy&pasted answeres to to Javascript:
var original = "[{\"place_id\":\"2413006\",\"licence\":\"Data \u00a9 OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap\/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);

which is successfull. displayname is shown.

converted and excaped unicode in json string makes no difference. Firefox displays correct letters.

in chrome the error is spelled: typeerror: undefined is not a function. IE: typeerror: das objekt unterstützt die Eigenschaft oder Methode "parse" nicht. Meaning: Object doesn't support property or method "parse".

what is wrong? Is the copy&paste converting something, i miss? What am I missing???

Share Improve this question edited Jan 18, 2015 at 15:05 Mouser 13.3k3 gold badges30 silver badges54 bronze badges asked Jan 18, 2015 at 14:59 Markus KrethMarkus Kreth 7481 gold badge8 silver badges27 bronze badges 3
  • Your " are being escaped. That shouldn't happen. – Mouser Commented Jan 18, 2015 at 15:05
  • are you sure you need those backslashes to escape " ? Maybe throws the error since I believe Ive never had to escape this – Ba5t14n Commented Jan 18, 2015 at 15:06
  • 1 Also if Chrome and IE are reporting JSON as undefined then you have either overwritten the native JSON function, or are using an out of date browser or there is another script error. – Mouser Commented Jan 18, 2015 at 15:12
Add a ment  | 

2 Answers 2

Reset to default 3

JSON.Parse does not exist in JavaScript, you want JSON.parse. Lower case p!

From what I can tell by your first code snippet arr = JSON.Parse(response);, you are attempting to use an uppercase version of JSON.parse. The second code snippet works just fine for me in all modern browsers. See documentation here. JavaScript is case-sensitive.

发布评论

评论列表(0)

  1. 暂无评论