0

I have following json file format.

{
  "browser": "firefox",
  "dateTime": "28_May_2014_03_35_PM"
}
{
  "browser": "firefox",
  "dateTime": "28_May_2014_03_36_PM"
}

as per requirement I cannot change it format, but I have to read this I know we can provide [ and ] braces and separate each element by , but I cant do this, my source file is having above format only.

so how can I read such file?

Is there any way to read such file and convert whole file content to valid json formatted content?

2
  • yes @Ehsan but Its source file...how do I read it? Commented May 30, 2014 at 5:48
  • 1
    You'll have to read it in as a String and then manually parse it. Commented May 30, 2014 at 5:49

2 Answers 2

2

you could try something like this

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>

<script>
  debugger;
  var input = '{  "browser": "firefox",  "dateTime": "28_May_2014_03_35_PM"  }  {    "browser": "firefox",    "dateTime": "28_May_2014_03_36_PM"  }';

  input = input.replace('}', '},');
  input = '[' + input + ']';

  var _json = JSON.parse(input);

  for (var i = 0; i < _json.length; i++)
    alert(_json[i].browser);
</script>
</body>
</html>

but if you have nested object inside will not work

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

Comments

2

If the file is exactly as you've presented it, then you can convert it into valid JSON and parse it.

var contents = JSON.parse("[" + fileContents.replace("}\n", "},\n", "g") + "]");

However, don't do this. If the invalid JSON file is being generated, look for ways to fix the code that's generating it. If it's a static file, fix it before continuing. Requirements are rarely set in stone.

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.