2012-11-21 60 views
4

我做一个winJS.xhr这样的JSON解析:如何在Windows 8

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 
+0

你可以简单地解析它在JavaScript obj = JSON.parse(json); json是json的对象...... – AurA

+2

@AurA:这没有用,他在他的问题的最后一行中是这样说的。 – Cerbrus

+0

json解析意外字符是由于解析已解析的对象...不是解析JSON字符串可以在[this post]中找到更多帮助(http://stackoverflow.com/questions/8524933/json-parse -unexpected-character-error) – AurA

回答

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是否为stringobject。 (如果它是一个字符串,我会说JSON.parse应该已经工作)
然后登录jsonResult本身,看看你是否可以通过它的属性。 (谷歌浏览器控制台的工作像这样的魅力)

如果它是一个字符串,这是一个(有点哈克,不安全)的方式来做到这一点:

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

(感谢@ ThiefMaster♦对于一些更合适(-ish)使用eval,而不是我自己的虐待它。)
然后,您应该能够访问result
一般情况下,你希望使用eval,但如果一切都失败了...

+0

我认为OP已经暗示他的'jsonResult'很可能是一个字符串,否则'jsonResult [0]'不会返回'{'。 – Passerby

+0

@Passerby:添加了一个选项,如果是这样的话。 – Cerbrus

+0

-1使用eval解析json,另一个-1如果我可以将变量赋值放入eval中。不幸的是,如果OP无法从远程系统获得有效的JSON,那么使用eval可能是一条路。嗯,仍然是-1的变量赋值里面的eval是丑陋/坏,不管是什么。但是,假设WinJS可以使用eval访问用户的*系统*,可能是任意的JS,这是一个非常糟糕的主意。 – ThiefMaster

6

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

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字符串应该使用双引号"附上一切可能的地方。

其实这也发生在PHPjson_decode

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

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

+0

- 它现在被修改为*稍微不那么危险*(tm) – Cerbrus

+0

@Cerbrus它是_tradition_说'eval'是危险的:)实际上[MDN建议'eval'在旧浏览器上模仿JSON] (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON#Browser_compatibility)。 – Passerby

+0

哦,如果MDN甚至使用'eval'(危险!),我想我们别无选择。 放弃希望,所有在这里'评估'的人。 – Cerbrus

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

    } 
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) { } 
); 
0

首先做的事:

jsonResult = JSON.parse(response.responseText); 

,然后你可以使用:

var rhs = jsonResult.rhs;