开发者

Parsing a malformed jSon string

I'm using a Java Json library to convert an incoming string into a json one. The lib is json-lib.

The problem is that I can't modify the source so, sometimes I can get some malformed jSon strings especially this kind of key/value strings :

"key":"a quoted "value" "

(this is a simplified example)

As you can see, there are double quotes surrounding the value.

So, is there an API that can replace automatically the inner double quotes with backslash ones?

Thank y开发者_运维技巧ou.


Well, there can't be. For example, what does the following (malformed example) mean:

"key":"is this a value?","another key":"is this a value too?"

In your condition it might be either:

"key":"is this a value?","another key":"is this a value too?"
^k1   ^v1                ^k2           ^v2

or:

"key\":\"is this a value?\",\"another key":"is this a value too?"
^k1                                        ^v1


You could write a simple parser which looks for " which is not followed by a ,, : or a } or other valid character and quote it and the next " occurrence. That would leave MByD's example untouched, but change you example.


If you are sure that there is no keys containnig ':' and ',' you can use following:

String repaired = broken.replaceAll("([^,{:])\"([^,:]})", "$1\\\\\"$2");

Here we escape only that quotes that are not following ',' ':' and '{' and not followed by ',' ':' '}'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜