将对象字符串转换为 JSON [英] Convert object string to JSON

查看:78
本文介绍了将对象字符串转换为 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 JavaScript(或 jQuery)将描述对象的字符串转换为 JSON 字符串?

How can I convert a string that describes an object into a JSON string using JavaScript (or jQuery)?

例如:转换这个(不是一个有效的 JSON 字符串):

e.g: Convert this (NOT a valid JSON string):

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"

进入这个:

str = '{ "hello": "world", "places": ["Africa", "America", "Asia", "Australia"] }'

如果可能,我希望避免使用 eval().

I would love to avoid using eval() if possible.

推荐答案

如果字符串来自可信来源,您可以使用 eval 然后使用 JSON.字符串化 结果.像这样:

If the string is from a trusted source, you could use eval then JSON.stringify the result. Like this:

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
var json = JSON.stringify(eval("(" + str + ")"));

注意,当你eval一个对象字面量时,它必须用括号括起来,否则括号会被解析为一个块而不是一个对象.

Note that when you eval an object literal, it has to be wrapped in parentheses, otherwise the braces are parsed as a block instead of an object.

我也同意问题下的评论,即开始时只用有效的 JSON 编码对象会更好,避免解析、编码,然后大概解析它再次.HTML 支持单引号属性(请确保对字符串中的任何单引号进行 HTML 编码).

I also agree with the comments under the question that it would be much better to just encode the object in valid JSON to begin with and avoid having to parse, encode, then presumably parse it again. HTML supports single-quoted attributes (just be sure to HTML-encode any single quotes inside strings).

这篇关于将对象字符串转换为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆