Parsing malformed JSON with Javascript

后端 未结 7 1766
抹茶落季
抹茶落季 2020-12-21 11:34

I want to parse this content using Javascript. The data looks like this:

{\"ss\":[[\"Thu\",\"7:00\",\"Final\",,\"BAL\",\"19\",\"ATL\",\"20\",,,\"56808\",,\"PRE

7条回答
  •  暖寄归人
    2020-12-21 11:59

    Let's assume you already have a valid JSON String (jsonString) to parse. (If you don't know how to retrieve a String to parse using XMLHttpRequest from the given url you will have to look into that first.)


    With plain JavaScript you will have to add Douglas Crockford's JSON library (or something similar) in order to provide a parsing Function if there is no native implementation:

    var json = json_parse(jsonString) ;
    
    • link

    With a JavaScript library like jQuery this would be

    var json = $.parseJSON(jsonString) ;
    

    Now, traversing the resultant JSON Object is a whole other issue, because you will have to know its structure before you can retrieve specific data. In this particular case -- if it was indeed well formed -- you would have to do the following:

    var data = json.ss ;
    
         for(var i = 0 ; i < data.length ; i++) {
    
              var entry = data[i] ;
    
              var day = entry[0] ; //!! the Arrays seem to have a format where the first entry always contains the data and so forth...
              /* ... */
    
              // then do something with the data bits
    
         }
    

提交回复
热议问题