javascript - d3.json console.log 返回未定义或 JSON.parse 在第 1 行返回意外字符

标签 javascript json parsing d3.js console

我花了很多时间试图解决此语句中的错误,以在 console.log 中显示 json url 的内容:

d3.json( urlpathtojson, function(error, jsondata ) {
    var jsonfile = JSON.parse(jsondata);
    console.log(jsonfile);
    }):

我可以看到 GET 语句和 JSON 请求的内容,但控制台给出以下错误:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

或者在其他情况下不解析:

ReferenceError: jsondata is not defined

或者

jsondata is undefined

以下是我在 Stackoverflow 上找到的答案。希望它也能对其他人有所帮助。

最佳答案

问题是控制台日志语句运行时没有等待 json 文件的返回,从而导致上述错误。

通过 Stackoverflow,我从这个问题中找到了这个解决方案: Returning array from d3.json()

function doSomethingWithData(jsondata) {
  console.log(jsondata);
}

d3.json(dataPath, doSomethingWithData);

注意 doSomethingWithData 是如何直接传递给 d3.json 的,而不是在匿名内部函数中单独调用它。

注意:这不是 d3.js 的特定问题。基本上,所有异步 javascript 函数都可能以类似的方式运行。如果它们返回某些内容,则它不会是传递的回调的返回值。

关于javascript - d3.json console.log 返回未定义或 JSON.parse 在第 1 行返回意外字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25272479/

相关文章:

java StreamTokenizer 解析器

javascript - 访问文件数据时出现问题

javascript - Highchart 十字准线不接触 x 轴

javascript - 迭代对象属性/键

javascript - 将整个 redux 状态作为单独的 JSON 文件获取

mysql - 这是在MySQL中存储JSON的合理用例吗?

excel - 如何在 Azure 逻辑应用中解析 Excel 电子表格

javascript - 如何阅读这个 JSON?

json - Xamarin & Golang - { []} 无效字符 '\x00' 寻找对象键字符串的开头

java - 数学表达式解析器