Skip to content

Instantly share code, notes, and snippets.

@loverde
Forked from kekscom/FixJson.js
Created January 4, 2019 19:46
Show Gist options
  • Select an option

  • Save loverde/062f732dba8d29165db667348fb76601 to your computer and use it in GitHub Desktop.

Select an option

Save loverde/062f732dba8d29165db667348fb76601 to your computer and use it in GitHub Desktop.

Revisions

  1. Jan Marsch renamed this gist Apr 16, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. Jan Marsch created this gist Apr 16, 2014.
    43 changes: 43 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    var json = '...'; // your truncated json data here

    var chunk = json;

    var m, q = false;
    var stack = [];

    while (m = chunk.match(/[^\{\[\]\}"]*([\{\[\]\}"])/)) {
    switch (m[1]) {
    case '{':
    stack.push('}');
    break;
    case '[':
    stack.push(']');
    break;

    case '}':
    case ']':
    stack.pop();
    break;

    case '"':
    if (!q) {
    q = true;
    stack.push('"');
    } else {
    q = false;
    stack.pop();
    }
    break;
    }
    chunk = chunk.substring(m[0].length);
    }

    if (chunk[chunk.length-1] === ':') {
    json += '""';
    }

    while (stack.length) {
    json += stack.pop();
    }

    // JSON.parse(json);