Tallboy
Tallboy

Reputation: 13407

Ignoring regex at end of string

I have an invalid JSON response like this:

{"a": 1, "b": {...}}{"x": 2, "y": 3}

I'm unable to fix the source, so I have to fix it on my end.

I want to extract out only this JSON chunk: {"a": 1, "b": {...}}

It's because it's appending a second chunk of metadata JSON {"x": 2, "y": 3} that I want to ignore.

How do I format my regex to either

a) only take the first JSON blob (up until the space right before the last {)

b) strip out the last JSON chunk (I would say look for the last { in the string so I can split right before it.

Method B is probably easiest

Upvotes: 0

Views: 82

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

You could use a regular expression, but it's more direct to just pull out the string you want.

str = '{"a": 1, "b": {"c": 2}}{"x": 2, "y": 3}'

s = str[0, str.index('}{')]
  #=> "{\"a\": 1, \"b\": {\"c\": 2}"

puts s
  #=> {"a": 1, "b": {"c": 2}

Here I've assumed that, as in the example, there are no spaces between the braces in '}{'. If there may be zero or more spaces, as here:

str = '{"a": 1, "b": {"c": 2}}   {"x": 2, "y": 3}'

use the following (which, alas, uses a regex, albeit a simple one):

puts str[0, str.index(/\} *\{/)]
  #=> {"a": 1, "b": {"c": 2}

Upvotes: 1

Simple Lime
Simple Lime

Reputation: 11035

As far as I can think right now, you'll never have an open bracket next to a close bracket in JSON, so you might be able to get away with just a simple split:

source = '{"a": 1, "b": {"c": 2}}{"x": 2, "y": 3}'
json = source.split(/(?<=\})\s*\{/)[0]
JSON.parse(json)
# => {"a"=>1, "b"=>{"c"=>2}}

Upvotes: 2

Related Questions