2

I actually receive this format of JSON format:

{ "bank": "CityBank", "sum": "500" }, { "bank": "WPBank", "sum": "700" }

But is can't be parsed without [] brackets. The result should be:

[{ "bank": "CityBank", "sum": "500" }, { "bank": "WPBank", "sum": "700" }]

How to add these brackets in JS?

9
  • 7
    Where are you getting the broken JSON from? The problem should be fixed at the source. The first sample simply is not JSON. Commented Mar 19, 2019 at 3:35
  • 6
    The former is not JSON. Recommended way would be to correct the API from where you get such response. Commented Mar 19, 2019 at 3:35
  • 1
    let parsed = JSON.parse(`[${notJSON}]`); Commented Mar 19, 2019 at 3:37
  • How does this even come back from a response? Usually if there's invalid JSON, nothing comes back at all. Commented Mar 19, 2019 at 3:37
  • @Scrimothy - clearly the API returns text - which can be anything, even not JSON :p Commented Mar 19, 2019 at 3:38

1 Answer 1

4

You can just take the invalid JSON and parse correctly it using JSON.parse:

let invalid = '{ "bank": "CityBank", "sum": "500" }, { "bank": "WPBank", "sum": "700" }';
let valid = JSON.parse("[" + invalid + "]");
console.log(valid);

Sign up to request clarification or add additional context in comments.

3 Comments

This is cool-- I didn't know that JSON.parse could work around invalid JSON. What are the limits on this? Is there some known degree/manner that input can be malformed at which JSON.parse will fail?
No, JSON.parse above is not parsing invalid JSON - it's parsing an invalid JSON string which I have concatenated into a valid JSON string by adding square brackets.
No problem @AlexanderNied, always glad to help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.