JSON.stringify /使用引号解析奇数 [英] JSON.stringify / parse oddness with quote marks

查看:77
本文介绍了JSON.stringify /使用引号解析奇数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在解析一些带引号的JSON时遇到了一个奇怪的小问题。我使用本机JSON.stringify和JSON.parse函数来执行此操作。如果我将一个带有引号的对象的字符串字符串化,它们就像人们期望的那样被转义。如果我然后将它解析回一个对象,它再次正常工作。

I am running into an odd little problem with parsing some JSON which has quotes in it. I am using the native JSON.stringify and JSON.parse functions to do this. If I stringify an object which an object which has quote marks in it, they are escaped as one would expect. If I then parse this back into an object, it again works fine.

问题发生在我进行字符串化,然后将对象打印到页面,然后解析结果串。如果我尝试这样做,解析函数将失败,因为stringify只在每个违规引号之前放置了单斜杠。

The problem is occurring where I stringify, then print the object to a page, then parse the resulting string. If I try to do this, the parse function fails as stringify has only put single slashes before each of the offending quote marks.

我需要实现这一点的原因是我正在开发一个应用程序,它将存储在数据库中的内容动态加载为JSON字符串。某些点上的字符串需要打印到页面某处,以便javascript可以找到它们并根据其内容构建页面。我需要一些方法可以强健地将对象传入和传出字符串,如果用户输入错误的字符,这些字符串不会失败!

The reason I need to achieve this is I am working on an application that dynamically loads content stored in a database as JSON strings. The strings at some point need to be printed onto the page somewhere so that the javascript can find them and build the page based on their contents. I need some way of robustly passing the object into and out of strings which will not fail if a user inputs the wrong characters!

我可以通过插入来解决这个问题使用替换调用对代码进行额外的斜杠,但我想知道是否有更好的方法来处理这个问题?

I can solve this for the moment by inserting extra slashes into the code with a replace call, but I was wondering if there is a better way to handle this?

我已经整理了几个jsfiddles来说明什么我想描述一下:

I have put together a couple of jsfiddles to illustrate what I am trying to describe:

http://jsfiddle.net / qwUAJ / (Stringify然后解析)

http://jsfiddle.net/qwUAJ/ (Stringify then parse back)

var ob = {};
ob["number1"] = 'Number "1"';
ob["number2"] = 'Number 2';
ob["number3"] = 'Number 3';

var string = JSON.stringify(ob);
var reOb = JSON.parse('{"number1":"Number \"1\"","number2":"Number 2","number3":"Number 3"}');

$('div').html(string);

http://jsfiddle.net/a3gBf/4/ (Stringify,然后打印,然后再解析)

http://jsfiddle.net/a3gBf/4/ (Stringify, then print, then parse back)

// Make an object
var ob = {};
ob["number1"] = 'Number "1"';
ob["number2"] = 'Number 2';
ob["number3"] = 'Number 3';

// Turn the object into a JSON string
var string = JSON.stringify(ob);

// Printing the string outputs
// {"number1":"Number \"1\"","number2":"Number 2","number3":"Number 3"}
$('.stringified').html(string);

// Attempt to turn the printed string back into an object
var reOb = JSON.parse('{"number1":"Number \"1\"","number2":"Number 2","number3":"Number 3"}');

// This fails due to the single escaped quote marks.

感谢您提前获得任何帮助!

Thank you for any help in advance!

推荐答案

这是一个问题,它来自于重新评估 String 而没有先将其转换回字符串文字,所以意味着如果它仍然有效则会发生变化。

您需要考虑'\'的字面意思是什么?答案是,没有 \ 。为什么?

This is a problem which arises from re-evaluating a String without first converting it back into a string literal, so the meaning changes if it is even still valid.
You need to consider what does '\"' as a literal actually mean? The answer is ", without the \. Why?


  • \解析为

  • \" resolves to "

如果你想要 \作为文字的结果,你需要写'\\\'

If you want to have \" as the result of the literal, you need to write '\\\"'


  • \\ 解析为 \

  • \解析为

  • \\ resolves to \
  • \" resolves to "

所以基本上,需要额外的斜杠来转义字符串文字中具有特殊含义的任何字符。

So basically, the extra slashes are required to escape any characters with special meaning in string literals.

如果你做了 var reOb = JSON.parse($('。stringified')。html()); 它可以正常工作。

If you did var reOb = JSON.parse($('.stringified').html()); it would work fine as is.

进一步考虑

str = '\\\"\\\'';      //      \"\'
str = '\"\'';          //      "'
str = '"'';            // SyntaxError: Unexpected token ILLEGAL






据我所知, JavaScript 没有提供原生实现来根据需要转换字符串,所以我所知道的最简单的方法是使用替换


As far as I'm aware, JavaScript offers no native implementation to convert strings as desired, so the easiest method I know of is using a replace

function toLiteral(str) {
    var dict = {'\b': 'b', '\t': 't', '\n': 'n', '\v': 'v', '\f': 'f', '\r': 'r'};
    return str.replace(/([\\'"\b\t\n\v\f\r])/g, function ($0, $1) {
        return '\\' + (dict[$1] || $1);
    });
}
toLiteral('foo\\bar'); // "foo\\bar"

这篇关于JSON.stringify /使用引号解析奇数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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