解析JSON字符串并显示它

时间:2015-06-07 19:04:28

标签: javascript json r d3.js

我是D3初学者(在JS中几乎没有经验)。我有以下几行代码:

<script type='text/javascript'> data ='{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16.46,"vs":0,"am":1,"gear":4,"carb":4,"_row":"Mazda RX4"},{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.875,"qsec":17.02,"vs":0,"am":1,"gear":4,"carb":4,"_row":"Mazda RX4 Wag"}';</script>

<script type="text/javascript">
 d3.select("body").append("div").text(JSON.parse(data));
</script>

总会产生以下错误:

Uncaught SyntaxError: Unexpected token ,     test-html:1

数据本身是通过R:

生成的
<!--begin.rcode results="asis", echo=FALSE, warning=FALSE, message=FALSE
library(RJSONIO)
  out <- paste("<script type='text/javascript'> data ='", gsub("\\[|\\]", "",jsonlite::toJSON(mtcars[1:2,])), "';</script>", sep="")
  cat(out)
end.rcode-->

这会导致您在第一个代码块(数据)中找到的JSON字符串。

任何人都可以弄清问题是什么?

谢谢!

1 个答案:

答案 0 :(得分:3)

var data不是有效的Json。 您应该在开始和结束处添加[]

var data ='[{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16.46,"vs":0,"am":1,"gear":4,"carb":4,"_row":"Mazda RX4"},{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.875,"qsec":17.02,"vs":0,"am":1,"gear":4,"carb":4,"_row":"Mazda RX4 Wag"}]';

加上JSON.parse(data)Objects中有2 data,而且不是字符串。