0

Because I work currently with an API returning JSON code I would need to get the whole JSON code returned by API and insert this code line by line (well formatted, if possible in an easy way) into a <pre> element.

My code I use at the moment:

$.getJSON(url + "api/get", function( data ) {

$.each(data, function(i, field){
  $("#result").append(field);
  console.log(field);
  }); 
});

Using the console output I get:

Object {message: "api key invalid"}

This seems to be strange, because when using postman to debug I get:

{"errors":{"message":"api key invalid"}}

How to get the response postman gets and how to insert this into my pre element, because at the moment this doesn't work too.

7
  • Why not skip the JSON parsing and just $.get() the content as raw text? Commented Jan 3, 2017 at 16:56
  • console.log(data) to see how the object looks then access the properties as needed. This might help ► stackoverflow.com/questions/10709241/… Commented Jan 3, 2017 at 17:09
  • @FrançoisWahl i already tried this too, it returns: [puu.sh/t9RTn/be6778344d.png](this). I just need to get the whole JSON object, so I can place this into a <pre> textbox, to show my users the whole reply from the API. Commented Jan 3, 2017 at 17:13
  • 1
    $("#result").append(JSON.stringify(data, null, 2)); Commented Jan 3, 2017 at 17:17
  • @FelixKling that would work of course but it'd lose any newline formatting that the real API response supplies. If the OP just wants the text I don't see why anything needs to treat it as JSON anyway. Commented Jan 3, 2017 at 17:20

1 Answer 1

1

Your $.each() loop is looping over every property in the response, and ignoring the property name.

You just want the whole data object, without any loops.

To display the message, check the object's properties.

Sign up to request clarification or add additional context in comments.

2 Comments

How to access them when using getJSON()?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.