[英]Can't get JSON file to parse into TableView in JavaScript using Appcelerator
[英]I can't parse using JSON using Javascript
我已經閱讀了這篇文章,但我仍然不知道發生了什么。
根據大多數JSON在線數據檢查器,我的var“文本”有效,但是當我執行解析時,它什么也沒做。
這是示例代碼:
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
var text = '{
"zipcodes": [
{
"zip": "22312",
"city": "Alexandria",
"state": "VA"
},
{
"zip": "22030",
"city": "Fairfax",
"state": "VA"
},
{
"zip": "22301",
"city": "Tyson's Corner",
"state": "VA"
},
{
"zip": "20148",
"city": "Ashburn",
"state": "VA"
}
]}';
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.zipcodes[1].zip + " " + obj.zipcodes[1].city;
</script>
</body>
</html>
您有兩個問題:
JavaScript不支持多行字符串,而無需在每行上都標記一個連續符(通過\\
在行末)。 我已經在示例中完成了此操作,但是將JSON包含在一行中確實更加容易。
您在字符串中使用了單引號,但字符串中包含未轉義的'
。 逃脫它,你很好。
var text = '{ \\ "zipcodes": [\\ { \\ "zip": "22312", \\ "city": "Alexandria", \\ "state": "VA" \\ }, \\ { \\ "zip": "22030", \\ "city": "Fairfax", \\ "state": "VA" \\ }, \\ { \\ "zip": "22301", \\ "city": "Tyson\\'s Corner", \\ "state": "VA" \\ }, \\ { \\ "zip": "20148", \\ "city": "Ashburn", \\ "state": "VA" \\ } \\ ]}'; obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.zipcodes[1].zip + " " + obj.zipcodes[1].city;
<div id='demo'></div>
您必須將json放在一行上並轉義'。
“泰森角”
http://jsbin.com/xumiba/1/edit?html,js,控制台,輸出
var text = '{ "zipcodes": [ { "zip": "22312", "city": "Alexandria", "state": "VA" }, { "zip": "22030", "city": "Fairfax", "state": "VA" }, { "zip": "22301", "city": "Tyson\'s Corner", "state": "VA" }, { "zip": "20148", "city":"Ashburn", "state": "VA" }]}';
您需要在每個字符串的新行末添加\\並轉義'字符。 這樣的事情會做:
var text = '{\
"zipcodes": [\
{\
"zip": "22312",\
"city": "Alexandria",\
"state": "VA"\
},\
{\
"zip": "22030",\
"city": "Fairfax",\
"state": "VA"\
},\
{\
"zip": "22301",\
"city": "Tyson\'s Corner",\
"state": "VA"\
},\
{\
"zip": "20148",\
"city": "Ashburn",\
"state": "VA"\
}\
]}';
obj = JSON.parse(text);
console.log(obj.zipcodes[1].zip + " " + obj.zipcodes[1].city);
document.getElementById("demo").innerHTML =
obj.zipcodes[1].zip + " " + obj.zipcodes[1].city;
這是一個jsfiddle鏈接:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.