1

I have string object but and stored in variable pass from another class. How can I add comma in between two object but not last object. The following below is my code.

{
        "id":"57e4d12e53a5a",
        "body":"asdas",
        "published":"Fri, 
        23 Sep 2016 06:52:30 +0000",
        "type":"chat-message",
        "actor":
            {
            "displayName":"beau",
            "objectType":"person",
            "image":
                {
                "url":"http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=80&d=mm&r=g",
                "width":48,"height":48
                }
            }
    }
    {
        "id":"57e4d51165d97",
        "body":"jackiechanSADAS",
        "published":"Fri, 23 Sep 2016 07:09:05 +0000",
        "type":"chat-message",
        "actor":
            {
                "displayName":"beau",
                "objectType":"person",
                "image":
                    {
                        "url":"http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=80&d=mm&r=g",
                        "width":48,
                        "height":48
                    }
            }
    }
    {
        "id":"asas",
        "body":"peterting",
        "published":"Fri, 23 Sep 2016 07:09:05 +0000",
        "type":"chat-message",
        "actor":
            {
                "displayName":"beau",
                "objectType":"person",
                "image":
                    {
                        "url":"http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=80&d=mm&r=g",
                        "width":48,
                        "height":48
                    }
            }
    }

How can I add comma "," in between of object but not last object by using programming because the whole thing I store it as string and without "," I can't parse it to object.

3
  • 2
    Why not just edit the string to valid JSON instead Commented Sep 23, 2016 at 7:46
  • Try String.replace('}{' , '},{'); Commented Sep 23, 2016 at 7:49
  • @Pugazh your code will not work because there are spaces and newlines between } and {. Commented Sep 23, 2016 at 7:51

1 Answer 1

7

You can use Regex for this:

JSON.parse('[' + string.replace(/}\s*{/g, '},{') + ']');
Sign up to request clarification or add additional context in comments.

1 Comment

Solved it. Thanks

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.