0

I am given a JSON array with some values being empty. Instead of null, these values are currently just empty, which makes the JSON invalid. For example:

[
    "Name",
    ,
    "card",
    ,
    ,
    342,
    2334,
    0
]

If possible, I'm looking for a regular expression to replace the empty space with null:

[
    "Name",
    null,
    "card",
    null,
    null,
    342,
    2334,
    0
]

The new lines and indentation are not present in the actual JSON.

4
  • What language are you using? Commented Apr 17, 2014 at 0:17
  • I'm using Java regular expressions. Commented Apr 17, 2014 at 0:19
  • 2
    ,, => ,null, and ,] => ,null]? Commented Apr 17, 2014 at 0:24
  • 1
    What if I had ,,,? It would replace it with ,null,, but there would still be two consecutive commas left. Commented Apr 17, 2014 at 0:31

2 Answers 2

3

Try replacing any empty string or whitespace preceded and followed by a comma (or by [ or ] if it occurs exactly at the beginning or end of the list) with null. It should work whether the actual JSON string has whitespace or not.

String result = str.replaceAll("(?<=,|\\[)\\s*(?=,|\\])","null")
Sign up to request clarification or add additional context in comments.

5 Comments

Wouldn't this one just remove the fields instead of replacing with null? Shouldn't it be replaced by "null,"?
This is right now. I missed the note of no whitespace in OP, but I'll leave my answer up there for reference.
+1. This works for the sample input. But won't replace if it's the first one, which OP doesn't mention. :)
@BheshGurung: you're correct, it wouldn't work if it's the last either, edited.
What about inside a string?
0

Note: This works if you have whitespace like in your OP. Otherwise, you'll want to use @anana's answer or @BillCriswell's comment.

Replace:

^(\s*)(?=,)

With:

$1null

This looks at the beginning of each line (^), followed by capturing 0+ whitespace characters ((\s*)), while looking ahead to see that the next character is a comma ((?=,)).

This will need to be a global match (g modifier) and, depending on the language, you may need to make ^ match each new line (m modifier).

Example: Regex101

1 Comment

I think this wouldn't work as there is no whitespace in the actual file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.