JSON.parse以字符串形式出现

时间:2014-04-13 02:21:00

标签: javascript node.js express pug

我已经意识到我的初始帖子不够清楚,所以这里有更多细节。

玉:

meta(name='revObj', content=(JSON.stringify('#{rev[1]}')))

HTML中的玉的结果:

<meta name="revObj" content=""{ companyAddress: '',\n endDate: '2008',\n startDate: '2005',\n companyName: '',\n description: 'This should be last. Want to go reverse chronological order with current or recent work/education at top. Also%2C some people will want their education first.',\n companyDescription: '',\n position: 'Freelance Programmer',\n _id: 534735ef48dfc379c76a1854,\n __v: 0,\n revisions: [],\n comments: [],\n successExamples: [] }"">

这就是js被调用的方式。

<li onclick="changeRev(this,'next')">newer</li>

JS:

function changeRev(target, action){
    var container = target.getElementsByTagName('meta').revObj;
    var data = JSON.parse(container.content);
    console.log(data);
    console.log(typeof data);
}

所以我有这两件事。当我尝试运行js时,它能够从元标记中获取内容,但是当我执行JSON.parse时,它会打印出看起来像对象但typeof返回一个字符串。有什么想法吗?

响应中的注释是console.log(数据);打印出来:

{ companyAddress: '',
  endDate: '2008',
  startDate: '2005',
  companyName: '',
  description: 'This should be last. Want to go reverse chronological order with current or recent work/education at top. Also%2C some people will want their education first.',
  companyDescription: '',
  position: 'Freelance Programmer',
  _id: 534735ef48dfc379c76a1854,
  __v: 0,
  revisions: [],
  comments: [],
  successExamples: [] }

使用console.log(typeof date);打印:

string

json的东西本身是从mongdb加载的。

编辑:我发现答案很简单,纯粹与玉石有关。问题是html最终以content = double引号打破了它。 JSON.stringify(rev [1])是玉器方面所需要的。

感谢大家的帮助。

1 个答案:

答案 0 :(得分:2)

你所做的事情有很多不妥之处。

  1. 您将JSON对象作为HTML对象的属性传递。您需要转义引号或失败(例如"应为\")。
  2. 密钥需要包含在转义引用中。
  3. target未指定,我将假设它是head容器
  4. 您尝试引用名称为meta的{​​{1}}代码,但不是这样做的,revObj会返回包含该代码的所有元素,你需要做的是迭代document.getElementsByTagName并获得document.getElementsByTagName('meta')的那个。
  5. 始终为JSON使用双引号,而不是单引号。
  6. 你不应该像这样传递一个name === "revObj"对象。有这个特殊原因吗?我不完全确定有什么对你有用。
  7. 使用它来验证您的JSON:http://jsonlint.com/

    修改: 根据 Cookie怪物的评论,JSON将在实时列表中使用。