在JS中解析JSON字符串[已关闭]

问题描述 投票:0回答:1

在 JS 文件中我有:

{html: 'Test code HTML', css: 'Test code CSS'}

我如何解析它以获得

html
css
的值?

这是我尝试过的:

const json = JSON.parse(data);
console.log(json.html);
console.log(json.css);

但是给了我这个错误:

Error: SyntaxError: "[object Object]" is not valid JSON at JSON.parse (<anonymous>)
javascript json
1个回答
-2
投票

接下来的代码是一个JS对象:

{html: 'Test code HTML', css: 'Test code CSS'}

前一个对象的预期 json 将是:

"{\"html\":\"Test code HTML\",\"css\":\"Test code CSS\"}"

将 JS 对象转换为 JSON 的方法是:

const data = {html: 'Test code HTML', css: 'Test code CSS'}

const json = JSON.stringify(data)

将 JSON 转换为 JS 对象是:

const jsonData = "{\"html\":\"Test code HTML\",\"css\":\"Test code CSS\"}"

const jsObject = JSON.parse(data)
© www.soinside.com 2019 - 2024. All rights reserved.