Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

337
Views
Difference between JSON.parse and .json() in Javasscript

I have a simple angular2 http get call like below

import { Http, Response } from '@angular/http';
@Injectable()
export class ServiceBase {
  protected resource: string;
  constructor(private _http: Http) { }

  getTnCByCountryCodeNdType(countryCode: string, tncType: string) {
        let url = `${CONFIG.URL}/tnc?countryCode=${country}&tnc=${tnc}`;

        return this._http.get(url, this.getHeader())
                    .map((res: Response) => {
                        return res.json();
                    });
    }
}

The Error response from the above when received,

I tried

this.service
      .getTnCByCountryCodeNdType('MY', this.tnc.toLowerCase())
              .subscribe(x => {
                //
              },
              (err: Response) => {
                error = JSON.parse(err);
              });

where: err is the response error;

and it threw the usual json error .

EXCEPTION: Unexpected token R in JSON at position 0

To my surprise

error = err.json();

Works fine. What is the difference between the two and why does the first one failed? Any help is appreciated

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

JSON.parse is a JavaScript thing. It parses a string containing JSON into whatever that string represents. You don't pass it objects. Clearly, your err isn't a string.

The res and err that Angular 2's http gives you are Response objects, which says it derives from Body. I can't see anything in the Angular 2 docs saying what Body is, but clearly it has a json function that returns the result of parsing the response data as JSON. That's not a JavaScript thing, that's something from Angular. (As noted in the link above, it's inspired by — but not the same as — fetch.)

over 4 years ago · Santiago Trujillo Report

0

JSON.parse expects a JSON-formatted string, but you give it a Response object, which is not JSON, hence the parsing error.

res.json() extracts the JSON-formatted data from the Response object and converts the data into a JavaScript object.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!