0

I have a button that invokes a POST call which retrieves a json response from the server. I'd like to open a new (chrome) browser tab with this json response.

This is what I have so far in angular

$http.post(url,data)
  .then(function(res) {
    $scope.toJSON = angular.toJson(res.data);
    var blob = new Blob([$scope.toJSON], { type:"application/json;charset=utf-8;" });

    var downloadLink = angular.element('<a></a>');
    downloadLink.attr('href',window.URL.createObjectURL(blob));
    downloadLink.attr('target','_blank');
    downloadLink[0].click();
  })

This code will open a new tab with the json in it, but it doesn't seem to be recognized as json. What I mean by this is that I have a chrome extension (JSONView), which will automatically pretty print any json. But it doesn't seem to pretty print this one.

If it matters, the new tab has an url that looks like this

blob:chrome-extension://knecfkbfhnkfajaonlnodhpjpbbpjfcp/c3b7e4dc-8209-4d0f-8f79-d8ba25e960a2

I've tried a bunch of different chrome extensions for viewing json and they all exhibit the same effect. It's possible the extensions can't process this "blob:chrome-extension://" page.

So what's the right way to open a json in a new tab?

Clarification I don't want to display this on the page. I want to open it in a new tab. I should mention that this is code within a Chrome Extension, not a standard web page

1 Answer 1

1

Instead of using an extension you can use <pre> element and JSON.stringify()

fetch("https://gist.githubusercontent.com/guest271314/ffac94353ab16f42160e/raw/aaee70a3e351f6c7bc00178eabb5970a02df87e9/states.json")
.then(response => response.json())
.then(json => {
  document.querySelector("pre").textContent = JSON.stringify(json, null, 2)
})
<pre></pre>

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

4 Comments

Event simpler in angularjs since it has a built in json filter that parses and prettifies<pre>{{object|json}}</pre>
Just to clarify, I don't want to display it on the page. I want to open it in a separate tab.
You can use the same procedure, whether the <pre> element is at current document at current window or another document at a separate tab.
gotcha. so i need to create an html doc instead of a json doc to send to my new tab

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.