在 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>)
接下来的代码是一个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)