0

I'm facing a problem where I could not find a good looking approach to parse one string which contains multiple JSON strings, as in {content1}{content2}{content3}.

What is a good approach to parse this string so the result would be:

{content1} {content2} {content3}

Maybe something with Regex?

6
  • I would look into JSON.NET for parsing JSON strings into objects. Commented Mar 26, 2013 at 15:11
  • THis is not JSON format Commented Mar 26, 2013 at 15:11
  • @CuongLe This is just an example. The important part is the curly brackets, which would be used for the algorithm to know where one JSON starts and the other ends. Commented Mar 26, 2013 at 15:16
  • But can't the content bits also contain curly brackets, if they are supposed to be JSON? Commented Mar 26, 2013 at 15:27
  • No, not for my current use at least. Commented Mar 26, 2013 at 15:28

3 Answers 3

2

Maybe you can use string.Split:

var output = input.Split(new[] {'{', '}'}, StringSplitOptions.RemoveEmptyEntries)
                  .Select(x => "{" + x + "}")
                  .ToList();
Sign up to request clarification or add additional context in comments.

2 Comments

Out of curiosity, and for other who stumble upon this answer, what does that actually do?
@PeterHerdenborg: The code has shown what actually does, I can add the link for more clear
0

You can use RegEx:

string input = "{content1}{content2}{content3}";
var matches = Regex.Match(input, "(?:({[^}]+}) *)*");
string[] contents = matches.Groups[1].Captures.Cast<Capture>().Select(c => c.Value).ToArray();

3 Comments

In a case like { foo: { bar: 'null' } }{...}{...}, wouldn't your regexp stop matching prematurely, i.e. at the first } that it encounters?
Yes, it would. But sample input does not show any case like that.
Well, it seems there were no curly brackets inside after all.
0

If you know for sure that each JSON part is an object literal, I guess you can simply split the string on }\s*{, as that could never occur inside valid JSON.

Comments

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.