如何在Windows 8中解析JSON

时间:2012-11-21 07:59:44

标签: javascript windows json windows-8 winjs

我正在做这样的winJS.xhr:

var jsonResult;
WinJS.xhr(
{
    url: urlGoogle,
    responseType: 'json'
}
).done(function complete(response) {
    jsonResult = response.responseText;

    console.log(jsonResult);
}, 
//Error and Progress functions
);

控制台日志向我显示:

{lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: true}

我想得到rhs信息。 所以我试着做了

console.log(jsonResult.rhs); 

console.log(jsonResult['rhs']);

它只显示我“未定义”。然后我意识到,当我做了一个jsonResult [0]时,它会显示第一个字符(即{)等等,并带有索引括号。

我试着做一个JSON.parse(jsonResult);但它会产生错误

json parse unexpected character

6 个答案:

答案 0 :(得分:6)

您看到的字符串实际上并不是有效的JSON,因为它的属性名称未被引用。这就是JSON.parse抛出错误的原因。

答案 1 :(得分:2)

刚刚在Chrome开发工具上尝试过:

JSON.parse("{lhs: \"32 Japanese yen\",rhs: \"0.30613818 Euros\",error: \"\",icc: true}")
SyntaxError: Unexpected token l
JSON.parse('{lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: true}')
SyntaxError: Unexpected token l
JSON.parse('{lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: 1}')
SyntaxError: Unexpected token l
JSON.parse('{"lhs": "32 Japanese yen","rhs": "0.30613818 Euros","error": "","icc": true}')
Object
    error: ""
    icc: true
    lhs: "32 Japanese yen"
    rhs: "0.30613818 Euros"
    __proto__: Object

所以似乎“有效”的JSON 字符串应该使用双引号"来封闭每个可能的位置。

实际上这也发生在PHP的{​​{1}}。

我不知道Win8JS的开发,所以我不确定你是否可以使用json_decode或类似的东西,但直接解析response.responeJSON似乎可能会失败。

如果您确实需要使用response.responseText,请考虑@Cerbrus'危险的responseText方法。

答案 2 :(得分:1)

var test = {lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: true}
//test.lhs returns "32 Japanese yen"

我不太清楚为什么这不适合你。尝试记录console.log(typeof jsonResult)以查看jsonResult是string还是object。 (如果它是一个字符串,我会说JSON.parse应该工作)
然后记录jsonResult本身,看看你是否可以浏览它的属性。 (谷歌Chrome控制台就像这样的魅力)

如果它是一个字符串,这是一种(有点hacky,不安全)方式:

var result = eval('({lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: true})')
var result = eval('(' + jsonResult + ')')

(感谢@ ThiefMaster♦对eval使用result而不是我自己滥用它。(
然后,您应该可以访问eval 通常,您想要使用{{1}},但如果其他所有方法都失败了......

答案 3 :(得分:1)

在您的情况下,请检查以下

WinJS.xhr({ url: urlGoogle }).then(
           function completed(response) {
                var jsonString = JSON.parse(response.responseText);
                console.log(jsonString .rhs);
           },
           function error(error) { console.log(error) },
           function progress(progress) { }
);

OR

WinJS.xhr({ url: urlGoogle }).then(
           function completed(response) {
                var jsonString = JSON.parse(response.responseText);
                 console.log(jsonString .rhs); 
           },
           function error(error) { console.log(error) },
           function progress(progress) { }
);

答案 4 :(得分:0)

首先:

jsonResult = JSON.parse(response.responseText);

然后你可以使用:

var rhs = jsonResult.rhs;

答案 5 :(得分:-1)

我过去曾在博客中写过这篇文章。下面的代码调用一个返回JSON的Web服务。

这里解释: http://blogs.msdn.com/b/brunoterkaly/archive/2012/11/06/step-4-augmented-reality-windows-8-and-cloud-computing-how-to-implement-with-real-code-implementing-the-windows-8-client.aspx#

有关此代码的有用之处在于您“尝试”获取值。它们可能不存在。

请参阅parsedResults.TryGetValue()。

    private async System.Threading.Tasks.Task CallLocationWebService(string gps)
    {
        // Call into the emulator. This assumes you are running the
        // cloud project from the last post in the backgruond
        string _location = "http://127.0.0.1:81/api/values?location={0}";

        // You can use the line below once you deploy your cloud
        // application to the cloud (a MS data center)
        //string _location = "http://locationwebservice.cloudapp.net/api/values?location={0}";

        // Now make the aynchronous call. We need to pass the GPS
        // parameters here to the _location string mentioned above.
        using (HttpClient clientlocation = new HttpClient())
        using (var response = await clientlocation.GetAsync(string.Format(_location, gps)))
        {
            if (response.IsSuccessStatusCode)
            {
                string webresponse = await response.Content.ReadAsStringAsync();

                // Parse the string into a JSONObject
                var parsedResults = JsonObject.Parse(webresponse);

                IJsonValue val;

                // Extract data embedded in JSONObject.
                // Assign to controls in user interface
                if (parsedResults.TryGetValue("latitude", out val))
                    loc_info.latitude = val.GetString();
                if (parsedResults.TryGetValue("longitude", out val))
                    loc_info.longitude = val.GetString();
                if (parsedResults.TryGetValue("bus_and_neighborhood", out val))
                    loc_info.bus_and_neighborhood = val.GetString();
                if (parsedResults.TryGetValue("elevation", out val))
                    loc_info.elevation = val.GetString();
                if (parsedResults.TryGetValue("bus_and_neighborhood", out val))
                    loc_info.bus_and_neighborhood = val.GetString();
                if (parsedResults.TryGetValue("max_temp", out val))
                    loc_info.max_temp = val.GetString();
                if (parsedResults.TryGetValue("min_temp", out val))
                    loc_info.min_temp = val.GetString();

                this.bus_and_neighborhood.Text = loc_info.bus_and_neighborhood;
                this.elevation.Text = loc_info.elevation;
                this.latlong.Text = loc_info.latitude + "/" + loc_info.longitude;
                this.max_temp.Text = loc_info.max_temp;
                this.min_temp.Text = loc_info.min_temp;
            }
        }

    }