This algorithm is pretty straightforward--something like the following should work:

function parse(a) {
  //create object to return
  var ret = {
    columns: [],
    data: []
  };

  //iterate the source array
  a.forEach(function(item, i) {
    if (i === 0) {
      //first time through, build the columns
      for (var key in item) {
        ret.columns.push(key);
      }
    }

    //now build your data item
    ret.data[i] = [];

    //use the column array to guarantee that the order of the fields in the source string doesn't matter
    for (var j = 0; j < ret.columns.length; j++) {
      var key = ret.columns[j];
      ret.data[i].push(item[key]);
    }
  });
  return ret;
}

var j = {
  "d": "[{\"ID\":\"VN00000123\",\"NAME\":\"JOHN GREEN\",\"GENDER\":\"Male\",\"BIRTHDAY\":\"15-10-1987\"},{\"NAME\":\"MERRY BLUE\",\"BIRTHDAY\":\"03-12-1983\",\"ID\":\"VN00000456\",\"GENDER\":\"Female\"},{\"GENDER\":\"Male\",\"ID\":\"VN00000789\",\"NAME\":\"BLACK BROWN\",\"BIRTHDAY\":\"09-07-1990\"}]"
};

//j is an object with one property (d) that is a JSON string that needs parsing
var o = parse(JSON.parse(j.d));
console.log(o);

Answer from Dave on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › parse
JSON.parse() - JavaScript | MDN
JSON.parse() parses a JSON string according to the JSON grammar, then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the "__proto__" key — see Object ...
🌐
W3Schools
w3schools.com › js › js_json_parse.asp
JSON.parse()
JS Examples JS HTML DOM JS HTML Input JS HTML Objects JS HTML Events JS Browser JS Editor JS Exercises JS Quiz JS Website JS Syllabus JS Study Plan JS Interview Prep JS Bootcamp JS Certificate JS Reference ... A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON.parse(), and the data becomes a JavaScript ...
Discussions

jquery - How to parse JSON to JSON in javascript? - Stack Overflow
Somebody've ideas for this, share with me (using javascript or jquery). Thank you so much. ... First, you need to parse it using JSON.parse(obj.d). More on stackoverflow.com
🌐 stackoverflow.com
Javascript how to parse JSON array - Stack Overflow
There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified. There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. More on stackoverflow.com
🌐 stackoverflow.com
javascript - How to parse JSON string in Typescript - Stack Overflow
Is there a way to parse strings as JSON in TypeScript? For example in JavaScript, we can use JSON.parse(). Is there a similar function in TypeScript? I have a JSON object string as follows: {"... More on stackoverflow.com
🌐 stackoverflow.com
why is JSON.parse way slower than parsing a javascript object in the source itself?
These answers missed the most significant difference, run-time vs. compile time. There is a lot of overhead with parsing JSON since you are doing string parsing and constructing objects at runtime. The compiler cannot optimize this. Whereas, if you're loading a JS source file, the JIT compiler is able to kick in before the program is even executed. More on reddit.com
🌐 r/javascript
35
67
June 3, 2017
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-json-parse-method
JavaScript JSON parse() Method - GeeksforGeeks
July 11, 2025 - The JSON.parse() method is used to convert a JSON string into a JavaScript object.
🌐
DigitalOcean
digitalocean.com › community › tutorials › js-json-parse-stringify
How To Use JSON.parse() and JSON.stringify() | DigitalOcean
November 24, 2021 - JSON.parse() takes a JSON string and transforms it into a JavaScript object. let userStr = '{"name":"Sammy","email":"sammy@example.com","plan":"Pro"}'; let userObj = JSON.parse(userStr); console.log(userObj); Executing this code will produce the following output: Output{name: 'Sammy', email: ...
Top answer
1 of 3
3

This algorithm is pretty straightforward--something like the following should work:

function parse(a) {
  //create object to return
  var ret = {
    columns: [],
    data: []
  };

  //iterate the source array
  a.forEach(function(item, i) {
    if (i === 0) {
      //first time through, build the columns
      for (var key in item) {
        ret.columns.push(key);
      }
    }

    //now build your data item
    ret.data[i] = [];

    //use the column array to guarantee that the order of the fields in the source string doesn't matter
    for (var j = 0; j < ret.columns.length; j++) {
      var key = ret.columns[j];
      ret.data[i].push(item[key]);
    }
  });
  return ret;
}

var j = {
  "d": "[{\"ID\":\"VN00000123\",\"NAME\":\"JOHN GREEN\",\"GENDER\":\"Male\",\"BIRTHDAY\":\"15-10-1987\"},{\"NAME\":\"MERRY BLUE\",\"BIRTHDAY\":\"03-12-1983\",\"ID\":\"VN00000456\",\"GENDER\":\"Female\"},{\"GENDER\":\"Male\",\"ID\":\"VN00000789\",\"NAME\":\"BLACK BROWN\",\"BIRTHDAY\":\"09-07-1990\"}]"
};

//j is an object with one property (d) that is a JSON string that needs parsing
var o = parse(JSON.parse(j.d));
console.log(o);

2 of 3
2

You can try this example using jQuery:

https://jsfiddle.net/de02fpha/

var dump = {"d": "[{\"ID\":\"VN00000123\",\"NAME\":\"JOHN GREEN\",\"GENDER\":\"Male\",\"BIRTHDAY\":\"15-10-1987\"},{\"ID\":\"VN00000456\",\"NAME\":\"MERRY BLUE\",\"GENDER\":\"Female\",\"BIRTHDAY\":\"03-12-1983\"},{\"ID\":\"VN00000789\",\"NAME\":\"BLACK BROWN\",\"GENDER\":\"Male\",\"BIRTHDAY\":\"09-07-1990\"}]"};

var parse = function(json) {
  var columns = [];
  var data = [];
  $.each(json, function(index, row) {
    var element = [];
    for (var key in row) {
      if (columns.indexOf(key) == -1)	columns.push(key);
      element.push(row[key]);
    }
    data.push(element);
  });

  return {columns: columns, data: data};
};


var json = $.parseJSON(dump.d);
console.log(parse(json));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

🌐
JavaScript.info
javascript.info › tutorial › the javascript language › data types
JSON methods, toJSON
The value of meetup.date is a string, not a Date object. How could JSON.parse know that it should transform that string into a Date?
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Learn_web_development › Core › Scripting › JSON
Working with JSON - Learn web development | MDN
Here we're creating a JavaScript object, checking what it contains, converting it to a JSON string using stringify() — saving the return value in a new variable — then checking it again. In this lesson, we've introduced you to using JSON in your programs, including how to create and parse JSON, and how to access data locked inside it.
Find elsewhere
🌐
JSON Editor Online
jsoneditoronline.org › home › parse › parse-json
Parse JSON: What is JSON parsing and how does it work? | Indepth
August 23, 2022 - In practice, you will often fetch ... libraries. For example in plain JavaScript, you can use fetch: const response = await fetch(url) const json = await response.json()...
🌐
W3Schools
w3schools.com › jsref › jsref_parse_json.asp
JavaScript JSON parse() Method
More "Try it Yourself" examples below. The JSON.parse() method parses a string and returns a JavaScript object.
🌐
ScrapingBee
scrapingbee.com › webscraping-questions › json › how-to-parse-a-json-file-in-javascript
How to parse a JSON file in JavaScript? | ScrapingBee
In JavaScript, you can parse a JSON string using the JSON.parse() method. A JSON file is essentially a text file containing a JSON string.
🌐
Tutorial Republic
tutorialrepublic.com › javascript-tutorial › javascript-json-parsing.php
JavaScript JSON Parsing - Tutorial Republic
Whereas an example of JSON array would look something like this: ... Tip: A data-interchange format is a text format which is used to interchange or exchange data between different platforms and operating systems. JSON is the most popular and lightweight data-interchange format for web applications. In JavaScript, you can easily parse JSON data received from the web server using the JSON.parse() method.
🌐
Hostman
hostman.com › tutorials › how to parse json in javascript
JavaScript: How to Parse Json | Guide by Hostman
March 31, 2025 - External files are frequently used to store JSON data. In JavaScript, you may use asynchronous methods like fetch() or frameworks like Axios to get and parse JSON data from a file. Here's an example with fetch():
Price   $
Address   1999 Harrison St 1800 9079, 94612, Oakland
Top answer
1 of 12
395

TypeScript is (a superset of) JavaScript, so you just use JSON.parse as you would in JavaScript:

let obj = JSON.parse(jsonString);

Only that in TypeScript you can also have a type for the resulting object:

interface MyObj {
    myString: string;
    myNumber: number;
}

let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);

(code in playground)

2 of 12
130

Type-safe JSON.parse

You can continue to use JSON.parse, as TypeScript is a superset of JavaScript:

This means you can take any working JavaScript code and put it in a TypeScript file without worrying about exactly how it is written.

There is a problem left: JSON.parse returns any, which undermines type safety (don't use any).

Here are three solutions for stronger types, ordered by ascending complexity:

1. User-defined type guards

Playground

// For example, you expect to parse a given value with `MyType` shape
type MyType = { name: string; description: string; }

// Validate this value with a custom type guard (extend to your needs)
function isMyType(o: any): o is MyType {
  return "name" in o && "description" in o
}

const json = '{ "name": "Foo", "description": "Bar" }';
const parsed = JSON.parse(json);
if (isMyType(parsed)) {
  // do something with now correctly typed object
  parsed.description
} else { 
// error handling; invalid JSON format 
}

isMyType is called a type guard. Its advantage is, that you get a fully typed object inside truthy if branch.

2. Generic JSON.parse wrapper

Playground

Create a generic wrapper around JSON.parse, which takes one type guard as input and returns the parsed, typed value or error result:

const safeJsonParse = <T>(guard: (o: any) => o is T) => 
  (text: string): ParseResult<T> => {
    const parsed = JSON.parse(text)
    return guard(parsed) ? { parsed, hasError: false } : { hasError: true }
  }

type ParseResult<T> =
  | { parsed: T; hasError: false; error?: undefined }
  | { parsed?: undefined; hasError: true; error?: unknown }

Usage example:

const json = '{ "name": "Foo", "description": "Bar" }';
const result = safeJsonParse(isMyType)(json) // result: ParseResult<MyType>
if (result.hasError) {
  console.log("error :/")  // further error handling here
} else {
  console.log(result.parsed.description) // result.parsed now has type `MyType`
}

safeJsonParse might be extended to fail fast or try/catch JSON.parse errors.

3. External libraries

Writing type guard functions manually becomes cumbersome, if you need to validate many different values. There are libraries to assist with this task - examples (no comprehensive list):

  • io-ts: has fp-ts peer dependency, uses functional programming style
  • zod: strives to be more procedural / object-oriented than io-ts
  • typescript-is: TS transformer for compiler API, additional wrapper like ttypescript needed
  • typescript-json-schema/ajv: Create JSON schema from types and validate it with ajv

More infos

  • Runtime type checking #1573
  • Interface type check with Typescript
  • TypeScript: validating external data
🌐
npm
npmjs.com › package › parse-json
parse-json - npm
import parseJson, {JSONError} from 'parse-json'; const json = '{\n\t"foo": true,\n}'; JSON.parse(json); /* SyntaxError: Expected double-quoted property name in JSON at position 16 (line 3 column 1) */ parseJson(json); /* JSONError: Expected ...
      » npm install parse-json
    
Published   Apr 09, 2025
Version   8.3.0
Author   Sindre Sorhus
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-catch-json-parse-error-in-javascript
How to Catch JSON Parse Error in JavaScript ? | GeeksforGeeks
April 15, 2024 - Parse JSON in JavaScript, accepting a JSON string as input and returning a corresponding JavaScript object with two methods, using JSON.parse() for parsing JSON strings directly and employing the fetch API to parse JSON responses from web APIs.
🌐
Reddit
reddit.com › r/javascript › why is json.parse way slower than parsing a javascript object in the source itself?
r/javascript on Reddit: why is JSON.parse way slower than parsing a javascript object in the source itself?
June 3, 2017 -

I have 2MB of simple json (just an array of arrays) that I generate from a flask server and just dump into a javascript file to be executed by the browser. At first I did something like

var data = JSON.parse("{{json}}");

but then I realized I could just do

var data = {{json}};

for my simple data. I don't know if you can just dump json into javascript and get valid code, but I'm pretty sure that form my simple case it should work.

Here's my question: why does the first form take several seconds while the second is instantaneous (at least in chrome)? I would think that the parser for javascript would be more complex than the parser for JSON, and both would be implemented in native code, so where is this difference coming from?

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › stringify
JSON.stringify() - JavaScript | MDN
Properties are visited using the ... JSON.stringify on the same object will always produce the same string, and JSON.parse(JSON.stringify(obj)) would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable)....
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Errors › JSON_bad_parse
SyntaxError: JSON.parse: bad parsing - JavaScript | MDN
JSON.parse("[1, 2, 3, 4,]"); JSON.parse('{"foo": 1,}'); // SyntaxError JSON.parse: unexpected character // at line 1 column 14 of the JSON data · Omit the trailing commas to parse the JSON correctly:
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Response › json
Response: json() method - Web APIs | MDN
When the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data. ... const myList = document.querySelector("ul"); const myRequest = new Request("products.json"); fetch(myRequest) .then((response) => response.json()) .then((data) => { for (const product of data.products) { const listItem = document.createElement("li"); listItem.appendChild(document.createElement("strong")).textContent = product.Name; listItem.append(` can be found in ${product.Location}. Cost: `); listItem.appendChild(document.createElement("strong")).textContent = `£${product.Price}`; myList.appendChild(listItem); } }) .catch(console.error);