Title: How to make a JSON object out of getAllResponseHeaders method
Tags: javascript;json;google-chrome;google-chrome-extension;xmlhttprequest
Question: I am currently writing a google chrome extension, and I need to find out information about websites' response headers. In order to do this, I used the ```getAllResponseHeaders``` method, but I need to put it in a JSON object. Unfortunately, I keep getting the error message ```SyntaxError: Unexpected token D in JSON at position 0 at main```.

Here is the code I am using to do this so far:

```xmlhttp.open("GET", url, false);
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
        allResponseHeaders = xmlhttp.getAllResponseHeaders();
    }
};
xmlhttp.send();

var responseHeaders = JSON.parse(allResponseHeaders);
obj.headers = responseHeaders;
```

When I put an alert immediately after the ```allResponseHeaders = xmlhttp.getAllResponseHeaders();``` call, the alert shows that the call was a success; the response headers have all been retrieved. The first response header is the Date, which I think has to do with the ```Unexpected token D``` part of my error message, but I don't know why it won't parse properly. How do I fix this? Thanks in advance.

EDIT: I would like my JSON object to look something like this:

```{
  "headers": {
    "Date": "June 20, 2016",
    "Content-Type": "charset=UTF/8",
    ...
  }
}
```

Comment: JSON.parse() isn't going to work on a string that doesn't contain JSON...that's like asking why parseFloat() doesn't work on the string "hello".

Comment: What is your desired output format, specifically? Please [edit]  your question to show an example. Also, you might want to add `console.log(allResponseHeaders)` immediately after assigning the value to that variable, so that you can see what format it is in (I think it should be one header per line separated by carriage returns).

Comment: Is there anyway to convert it to a JSON string?

Comment: I edited to show you what the ideal json format should be, and yes it is giving me each field separated by a line

Here is the accepted answer: See https://msdn.microsoft.com/en-us/library/ms536428(v=vs.85).aspx. The return headers are a crlf delimited string where each line contains key values separated by a colon. You will probably have to adjust the code below to account for whitespace.

```var arr = allResponseHeaders.split('\r\n');
var headers = arr.reduce(function (acc, current, i){
      var parts = current.split(': ');
      acc[parts[0]] = parts[1];
      return acc;
}, {});
```

Comment for this answer: The first item of the return value is incorrect.

    {
        "": undefined
        connection: "Keep-Alive"
        content-length: "306"
        content-type: "text/html; charset=UTF-8"
        date: "Wed, 21 Oct 2020 07:42:37 GMT"
        keep-alive: "timeout=5, max=94"
        server: "Apache/2.4.41 (Win64) OpenSSL/1.1.1c PHP/7.2.26"
        x-powered-by: "PHP/7.2.26"
    }

Here is another answer: I use the following function to extract all response headers as JS object using ```getAllResponseHeaders()```:

```function getResponseHeaderMap(xhr) {
  const headers = {};
  xhr.getAllResponseHeaders()
      .trim()
      .split(/[\r\n]+/)
      .map(value =&gt; value.split(/: /))
      .forEach(keyValue =&gt; {
        headers[keyValue[0].trim()] = keyValue[1].trim();
      });
  return headers;
}
```


Here is another answer: Simplified version of the accepted answer and fixed issue reported by ```@Emrah Tuncel``` :
```
The first item of the return value is incorrect. { &quot;&quot;: undefined }
```
```// ES6:
const headers = request.getAllResponseHeaders().trim().split('\r\n').reduce((acc, current) =&gt; {
      const [x,v] = current.split(': ');
      return Object.assign(acc, { [x] : v });
}, {});
```


Here is another answer: You should put ```JSON.parse``` logic inside the callback ```onreadystatechange```, since Ajax is an asynchronous call and ```allResponseHeaders``` may not be initialized when you use it right after sending the http request.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 4, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:06/20/16', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><json><google-chrome><google-chrome-extension><xmlhttprequest>', 'Title': 'How to make a JSON object out of getAllResponseHeaders method', 'ViewCount': 2406, 'id': 37924305, 'user_AboutMe': None, 'user_AccountId': 5431734.0, 'user_DisplayName': 'Cameron Payton', 'user_Reputation': 362.0, 'user_Views': 31.0, 'user_id': 5285952.0}}