我在尝试解析 JSON 时遇到错误:
SyntaxError: Unexpected token u in JSON at position 0(…) eFormsAtoZIndex.aspx:6558
完整代码:http://pastebin.com/LXpJN8GF
相关代码:
$(document).ready(function() {
var rebuild = getParameterByName("rebuild");
var createdStructures = $('#AtoZContentDiv').children().length;
if ((rebuild !== undefined && rebuild !== null && rebuild.indexOf("true") === 0) || (createdStructures === 0)) {
// clean up pre-existing data
cleanUp();
// create container structure
createFormLinkContainers();
// Call SP web services to retrieve the information and create the A to Z
retrieveListData();
completeInitialization();
} else {
try {
aggregateAll = jQuery.parseJSON($('#hdnAggregateAll').val());
console.log(jQuery.parseJSON($('#hdnAggregateAll').val()));
aggregatePersonal = jQuery.parseJSON($('#hdnAggregatePersonal').val());
aggregateBusiness = jQuery.parseJSON($('#hdnAggregateBusiness').val());
ministryAggregate = jQuery.parseJSON($('#hdnMinistryAggregate').val());
caAggregate = jQuery.parseJSON($('#hdnCAAggregate').val());
sTaxAggregate = jQuery.parseJSON($('#hdnSTaxAggregate').val());
bTaxAggregate = jQuery.parseJSON($('#hdnBTaxAggregate').val());
leTaxAggregate = jQuery.parseJSON($('#hdnLETaxAggregate').val());
} catch (err) {
console.log(err);
}
var type = getParameterByName("filter");
}
$("#tab-all").click(function() {
loadit('all');
});
$("#tab-business").click(function() {
loadit('business');
});
$(document).on('click', '#tab-personal', function(e) {
loadit('personal');
});
buildFilterMenu();
loadit('all');
});
function createJSONStructure(title, desc, index, type, formLink, documentLink, pubType, processId, ministry, ca, stax, btax, letax) {
if (desc !== undefined && desc !== null) {
desc = desc.replace(/</g, "<").replace(/>/g, ">");
} else {
desc = "";
}
var typeArr = [];
type = type.replace(/&/, "&");
var tempType = type.split("&");
for (i = 0; i < tempType.length; i++) {
typeArr.push(tempType[i].trim());
}
if (formLink === undefined || formLink === null || formLink.length === 0) {
formLink = "";
}
if (documentLink === undefined || documentLink === null || documentLink.length === 0) {
documentLink = "";
}
// subject, business and life event taxonomies must cater for multiple entries
var staxStructure = buildTaxonomyJSONStructure(stax, "stax");
var btaxStructure = buildTaxonomyJSONStructure(btax, "btax");
var letaxStructure = buildTaxonomyJSONStructure(letax, "letax");
var json = {
'name': title,
'desc': desc,
'type': typeArr,
'pubType': pubType,
'pdflink': documentLink.split(",")[0].replace(/\'/g, "'"),
'formlink': formLink.split(",")[0].replace(/\'/g, "'"),
'processid': processId,
'index': index,
'ministry': ministry.replace(/\,/g, " "),
'ca': ca.replace(/\,/g, " "),
'stax': staxStructure,
'btax': btaxStructure,
'letax': letaxStructure
};
return json;
}
function completeInitialization() {
if (checkDataLoaded()) {
// add the Navigation to the containers once all the data is inserted
addNavigationToContainers();
var type = getParameterByName("filter");
if (type == null || type.length == 0) {
type = "all";
}
loadit(type);
buildFilterMenu();
filter(type);
$('#hdnAggregateAll').val(stringify(aggregateAll));
console.log(aggregateAll);
$('#hdnAggregatePersonal').val(stringify(aggregatePersonal));
$('#hdnAggregateBusiness').val(stringify(aggregateBusiness));
$('#hdnMinistryAggregate').val(stringify(ministryAggregate));
$('#hdnCAAggregate').val(stringify(caAggregate));
$('#hdnSTaxAggregate').val(stringify(sTaxAggregate));
$('#hdnBTaxAggregate').val(stringify(bTaxAggregate));
$('#hdnLETaxAggregate').val(stringify(leTaxAggregate));
} else {
retryCount += 1;
// Check that the maximum retries have not been exceeded
if (retryCount <= maxRetries) {
setTimeout("completeInitialization();", 1000 * retryCount);
}
}
}
谁能指出 JSON 结构或 JS 有什么问题,或者我如何调试其中的项目?
编辑(根据 Jaromanda X 和 CH Buckingham 的回复):
$('#hdnAggregateAll').val(JSON.stringify(aggregateAll));
console.log(aggregateAll); $('#hdnAggregatePersonal').val(JSON.stringify(aggregatePersonal)); $('#hdnAggregateBusiness').val(JSON.stringify(aggregateBusiness)); $('#hdnMinistryAggregate').val(JSON.stringify(ministryAggregate));
$('#hdnCAAggregate').val(JSON.stringify(caAggregate));
$('#hdnSTaxAggregate').val(JSON.stringify(sTaxAggregate));
$('#hdnBTaxAggregate').val(JSON.stringify(bTaxAggregate));
$('#hdnLETaxAggregate').val(JSON.stringify(leTaxAggregate));
错误:
10:42:24.274 TypeError: item is undefined
createFormLinks/<()eformsAtoZIndex.aspx:5644
.each()jquery-1.11.1.min.js:2
createFormLinks()eformsAtoZIndex.aspx:5638
processResult()eformsAtoZIndex.aspx:5507
m.Callbacks/j()jquery-1.11.1.min.js:2
m.Callbacks/k.fireWith()jquery-1.11.1.min.js:2
x()jquery-1.11.1.min.js:4
.send/b()jquery-1.11.1.min.js:4
1eformsAtoZIndex.aspx:5644:1
在线:
if (item.processid !== "0")
block 中:
function createFormLinks(formItems, index)
{
// create all links on the page and add them to the AtoZContent div for now
var parentContainer = $("#AtoZContentDiv");
if (parentContainer === null)
{
// if it doesn't exist, we exist cause I can't reliably add a new control to the body and get the display
// location correct
return;
}
// sort form link array first
formItems = sortResults(formItems, 'name', true);
var count = 0;
$.each(formItems, function(i, item)
{
var link;
count = count + 1;
//add links to parent container
if (item.processid !== "0")
{
link = item.formlink;
}
else if (item.pdflink !== "")
{
link = item.pdflink;
}
var container = $("#AtoZContent-" + index);
var itemType = "all";
if (item.type !== null && item.type !== undefined && item.type.length === 1) itemType = item.type[0];
var str = "<div id='divFormLink-" + index + "-" + count + "' type='" + itemType + "' ";
if (item.name !== undefined && item.name !== null)
{
str = str + " ministry='" + stripPunctuation(item.ministry) + "' ";
str = str + " ca='" + stripPunctuation(item.ca) + "' ";
// now, we need to handle these differently since they can have multiple values
str = str + " stax='";
for (i = 0; i < item.stax.length; i++)
{
str = str + stripPunctuation(item.stax[i]);
}
str = str + "' ";
str = str + " btax='";
for(i = 0; i < item.btax.length; i++)
{
str = str + stripPunctuation(item.btax[i]);
}
str = str + "' ";
str = str + " letax='";
for(i = 0; i < item.letax.length; i++)
{
str = str + stripPunctuation(item.letax[i]);
}
str = str + "' ";
}
str = str + " index='" + index + "' style='word-wrap: break-word;'></div>";
container.append(str);
var innerDiv = $("#divFormLink-" + index + "-" + count);
appendIcon(innerDiv, item.pubType);
innerDiv.append("<a id='formLink-" + index + "-" + count + "' href='" + link + "'>" + item.name + "</a>");
innerDiv.append("<div id='formDesc-" + index + "-" + count + "'>" + item.desc + "</div><br />");
});
}
最佳答案
在第 155 行你推送 json,即使它是未定义的。
if (pubType=="eForm" || pubType=="PDF") {
var json = createJSONStructure(title, desc, index, type.toLowerCase(), formLink, documentLink, pubType, processId, ministry, ca, stax, btax, letax);
}
formItems.push(json);
然后您将尝试获取未定义的 item.processid。
您可以在 if block 中定义变量,但在这种情况下您应该添加一些验证。
$.each(formItems, function(i, item) {
var link;
count = count + 1;
if (item == null) {
return;
}
//add links to parent container
if (item.processid !== "0")
...
});
关于Javascript - 解析 JSON 返回语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39573701/
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
我脑子里浮现出一些关于一种新编程语言的想法,所以我想我会尝试实现它。一位friend建议我尝试使用Treetop(Rubygem)来创建一个解析器。Treetop的文档很少,我以前从未做过这种事情。我的解析器表现得好像有一个无限循环,但没有堆栈跟踪;事实证明很难追踪到。有人可以指出入门级解析/AST指南的方向吗?我真的需要一些列出规则、常见用法等的东西来使用像Treetop这样的工具。我的语法分析器在GitHub上,以防有人希望帮助我改进它。class{initialize=lambda(name){receiver.name=name}greet=lambda{IO.puts("He
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我正在使用ruby1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案