我正在尝试解析 url 编码的正文内容,但没有成功,例如: "data={\"event\":\"INBOX\",\"from\":\"3323230\",\"to\":\"43434343357\",\"text\":\"Example text"}"
我在做: var myVar = JSON.parse(myUrlEncodedContenString)
请问有什么想法吗?
这基本上是正确的:
var myVar = JSON.parse(myUrlEncodedContenString);
但是您的字符串不是 JSON 对象。JSON 对象不能以“data=”开头。JSON 对象只是在“data=”之后开始的路径。所以首先提取从索引 5 开始的子字符串。只有以下部分是 JSON:
{\"event\":\"INBOX\",\"from\":\"3323230\",...}
此外,您的字符串中有错误。在一处缺少逃逸。
你有:
...\"Example text"}"
但它应该是:
...\"Example text\"}"
测试显示它是如何工作的(最后转义固定):
<script type="text/javascript">
var data = "data={\"event\":\"INBOX\",\"from\":\"3323230\",\"to\":\"43434343357\",\"text\":\"Example text\"}";
var jsonEscaped = data.substring(data.indexOf("=") + 1);
var result = JSON.parse(jsonEscaped);
console.log(result);
console.log(result.event);
console.log(result.from);
console.log(result.to);
console.log(result.text);
</script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句