how to read non standard json file using javascript or jquery

前端 未结 2 1138
粉色の甜心
粉色の甜心 2021-01-26 07:37

I have following json file format.

{
  \"browser\": \"firefox\",
  \"dateTime\": \"28_May_2014_03_35_PM\"
}
{
  \"browser\": \"firefox\",
  \"dateTime\": \"28_Ma         


        
相关标签:
2条回答
  • 2021-01-26 08:06

    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

    0 讨论(0)
  • 2021-01-26 08:14

    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.

    0 讨论(0)
提交回复
热议问题