简体   繁体   中英

Using regex to remove JSON quotes

I am being given some JSON from an external process that I can't change, and I need to modify this JSON string for a downstream Java process to work. The JSON string looks like:

{"widgets":"blah","is_dog":"1"}

But it needs to look like:

{"widgets":blah,"is_dog":"1"}

I have to remove the quotes around blah . In reality, blah is a huge JSON object, and so I've simplified it for the sake of this question. So I figured I'd attack the problem by doing two String#replace calls, one before blah , and one after it:

dataString = dataString.replaceAll("{\"widgets\":\"", "{\"widgets\":");
dataString = dataString.replaceAll("\",\"is_dog\":\"1\"}", ",\"is_dog\":\"1\"}");

When I run this I get a vague runtime error:

Illegal repetition

Can any regex maestros spot where I'm going awrye? Thanks in advance.

I believe you need to escape braces. Braces are used for repetition ( (foo){3} looks for foo three times in a row); hence the error.

Note: in this case it needs to be double escaping: \\\\{ .

{ and } in regex have special meaning. They are to mention allowed repetition of patterns. So they are to be escaped here.

Use \\\\{\\"widgets\\":\\"", "\\\\{\\"widgets\\": instead of {\\"widgets\\":\\"", "{\\"widgets\\": .

I do wonder if you're better off taking the code for JSONObject and modifying the toString() method to make this a more reliable transformation than using regexps. Here's the source code, and you're looking for invocations of the quote() method

Since the input string looks to be valid json, your best bet would be to parse it with an actual parser to a map-like structure. Regexes are not the right tools for this. Serializing this structure to to something not quite json would then be relatively simple.

Well, why don't you simply do the following?

1) Decode the first JSON (which is correct with quotes) into varJSON1

2) Get the String "blah" in varJSON1 into varJSON2

3) Then decode the varJSON2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM