user1768830
user1768830

Reputation:

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.

Upvotes: 0

Views: 761

Answers (5)

Brian Agnew
Brian Agnew

Reputation: 272297

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

Upvotes: 1

Jörn Horstmann
Jörn Horstmann

Reputation: 34014

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.

Upvotes: 1

William R
William R

Reputation: 185

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

Upvotes: 0

Naveed S
Naveed S

Reputation: 5236

{ 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\":.

Upvotes: 1

user1919238
user1919238

Reputation:

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: \\{.

Upvotes: 1

Related Questions