Как найти json в браузере

Время на прочтение
3 мин

Количество просмотров 31K

Сегодня я хочу рассказать о JsonDiscovery, браузерном расширении для просмотра JSON. Возможно вы скажете: «у нас и так полно подобных расширений!». Да, полно, но фичи JsonDiscovery отличают его от других и делают его действительно мощным.

Давайте же взглянем поближе…


Для демонстраций я использовал JSON-файл коллекции всех карт из проекта Hearthstone-DB (спасибо Ольге Кобец за идею). И вот как он выглядит, если открыть его в браузере с установленным JsonDiscovery:

all-cards.json проекта Hearthstone-DB открытый в браузере с установленным JsonDiscovery

На первый взгляд это всего лишь еще один раскрасчик JSON. Все потому, что большинство фич не на поверхности, чтобы не отвлекать вас от вашего JSON. Давайте их раскроем:

  • Простое копирование фрагментов JSON в буфер
  • Сигнатура структуры JSON
  • Трансформация JSON с помощью запроса
  • Подсказки при написании запроса к JSON
  • Настройка отображения данных из JSON
  • Шаринг «отчетов» по ссылке

Рассмотрим каждый пункт детальнее.

Простое копирование фрагментов JSON в буфер

Бывает что нужно скопировать фрагмент JSON’а, то есть некоторого вложенного объекта или массива. С JsonDiscovery это простая задача, так как каждый развернутый объект и массив имеют кнопки действий. Одна из них кнопка «ƒ» button, нажав которую можно скопировать JSON в компактном или форматированном виде:

Меню действий на раскрытом объекте

Сигнатура структуры JSON

Когда вы изучаете данные, полезно иметь представление об их структуре. Просто наведите на кнопку «S» в панели действий на развернутом объекте или массиве и вы увидите сигнатуру структуры поддерева, как примерно это выглядит в TypeScript:

Сигнатура структуры данных как в TypeScript, удобно для набора объектов

Вы так же можете навести на свойство или тип значения в сигнатуре структуры чтобы получить некоторые детали, например о том какие значения использовались для поля:

Быстрый обзор значений, использованных для поля

Запросы к JSON

Клик по кнопке «Make report» переводит вас на страницу, где вы можете делать запросы к вашему JSON и/или настраивать его отображение:

За кнокой «Make report» кроется возможность делать запросы

Для запросов используется язык Jora. Он частично основывается на синтаксисе JavaScript 2015+, но в большей степени, задуман быть компактным и выражать больше (в рамках задачи запроса к данным).

Обычно вам нужно только выбрать некоторое подмножество данных используя некоторый путь, вроде foo.bar.baz. Если ключ имеет запрещенные символы просто используйте [] (квадратные скобки), то есть foo['a key with whitespaces']. Все как в JavaScript, за исключением того, что не нужно переживать существует путь или нет:

Простой запрос в виде пути

Часто необходимо использовать фильтрацию или мапинг. Jora предоставляет .[] для фильтрации и .() для мапинга:

Запрос с фильтрацией и мапингом

Пример на скриншоте выше (cards.[health].({ name, health })) можно записать на JavaScript так:

cards.filter($ => $.health).map($ => ({ name: $.name, health: $.health }))

Что гораздо многословнее, не так ли?

Вы можете найти больше о самом Jora и его синтаксисе в его репозитории на github. (Кстати, у него так же есть CLI и песочница)

Подсказки при написании запроса к JSON

Эту фичу невозможно описать правильно. Это нужно попробовать самому. Хотя бы раз:

Настройка отображения данных

Когда вы выбрали необходимые данные из JSON, вы можете настроить их отображение. Например, вывести их таблицей, или списком, вроде такого:

К сожалению, на данный момент нет достаточной документации о том, как описывать отображение (все что можно найти, может быть найдено в репозитории discovery.js). Но я верю это исправится в ближайшем будущем.

Шаринг «отчетов» по ссылке


Это были наиболее впечатляющие фичи JsonDiscovery, но есть гораздо больше фич поменьше, потому что расширение и проекты, лежащие в его основе, создаются с вниманием к деталям. И я могу с уверенностью сказать, все это меняет опыт работы с JSON в браузере!

JsonDiscovery доступен как расширение к Chrome и Firefox, и разрабатывается exdis как проект с открытым исходным кодом. Расширение построено на основе проекта Discovery.js, который еще на раней стадии разработки, но уже полезен для проектов вроде JsonDiscovery. Так что ожидается больше улучшений и фич в будущем. Следите за анонсами!

It is not a programming question, but need your views in few words.

When we hit the JSON url in Broswer, it asks us to save the file.
Why this happens ?
Is there any way to view it on the page itself ?
Is there any addon available to view JSON file in browser?

Wladimir Palant's user avatar

asked Mar 27, 2012 at 11:39

Umesh Patil's user avatar

Umesh PatilUmesh Patil

10.4k16 gold badges51 silver badges79 bronze badges

9

In Chrome use JSONView
or Firefox use JSONView

Manse's user avatar

Manse

37.8k10 gold badges83 silver badges108 bronze badges

answered Mar 27, 2012 at 11:42

Vodun's user avatar

6

If you don’t want to install extensions, you can simply prepend the URL with view-source:, e.g. view-source:http://content.dimestore.com/prod/survey_data/4535/4535.json. This usually works in Firefox and Chrome (will still offer to download the file however if Content-Disposition: attachment header is present).

answered Mar 27, 2012 at 12:02

Wladimir Palant's user avatar

Wladimir PalantWladimir Palant

56.6k12 gold badges96 silver badges125 bronze badges

4

In Chrome, use JSONView to view formatted JSON.

To view «local» *.json files:
— after install You must open the Extensions option from Window menu.
— Check box next to «Allow Access to File URLs»
— note that save is automatic (i.e. no explicit save necessary)

Re-open the *.json file and it should be formatted.

answered Nov 3, 2015 at 16:59

jatal's user avatar

jataljatal

7801 gold badge10 silver badges19 bronze badges

json-ie.reg. for IE

try this url

http://www.jsonviewer.com/

answered Mar 27, 2012 at 11:52

Javascript Coder's user avatar

Javascript CoderJavascript Coder

5,6418 gold badges48 silver badges97 bronze badges

0

Well I was searching view json file in WebBrowser in my Desktop app, when I try in IE still same problem IE was also prompt to download the file.
Luckily after too much search I find the solution for it.

You need to :
Open Notepad and paste the following:

    [HKEY_CLASSES_ROOTMIMEDatabaseContent Typeapplication/json]
    "CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
    "Encoding"=hex:08,00,00,00
    

Save document as Json.reg and then right click on file and run as administrator.

After this You can view json file in IE and you Desktop WebBrowser enjoy :)

answered Feb 14, 2013 at 14:20

Naveed's user avatar

NaveedNaveed

4033 silver badges11 bronze badges

For Firefox’s Bookmarks JSON files, use this excellent Bookmarklet:

javascript:(function(){var E=document.getElementsByTagName('PRE')[0],T=E.innerHTML,i=0,r1,r2;t=new Array();while(/("uri":"([^"]*)")/g.exec(T)){r1=RegExp.$1;r2=RegExp.$2;if(/^https?:/.exec(r2)){t[i++]='['+(i)+']:<a href='+r2+'>'+r2+'</a>';}}with(window.open().document){for(i=0;t[i];i++)write(t[i]+'<br>');close();}})();

Source: «alterna» from forums.Mozillazine.org:
http://forums.mozillazine.org/viewtopic.php?p=5551705#p5551705

answered Jan 4, 2014 at 7:56

Jinx Dojo's user avatar

I have the Content-Type of my JSON-printing CGIs set to text/javascript.

Works fine for both displaying in browser (e.g. Firefox) and processing in script.

Of course there’s no syntax-highlighting in this case.

answered Mar 27, 2012 at 12:49

Michael Sandino's user avatar

Michael SandinoMichael Sandino

1,8081 gold badge13 silver badges10 bronze badges

If there is a Content-Disposition: attachment reponse header, Firefox will ask you to save the file, even if you have JSONView installed to format JSON.

To bypass this problem, I removed the header («Content-Disposition» : null) with moz-rewrite Firefox addon that allows you to modify request and response headers https://addons.mozilla.org/en-US/firefox/addon/moz-rewrite-js/

An example of JSON file served with this header is the Twitter API (it looks like they added it recently). If you want to try this JSON file, I have a script to access Twitter API in browser: https://gist.github.com/baptx/ffb268758cd4731784e3

answered Aug 22, 2015 at 14:03

baptx's user avatar

baptxbaptx

3,3286 gold badges32 silver badges42 bronze badges

I would also recommend to use Notepad++ with json-view extension. You get the extension here: https://sourceforge.net/projects/nppjsonviewer/
Install and restart Notepad++.
Then open json-file in Notepad and go to «extensions -> Json-Viewer — > Format JSON. Then you habe the hierarchical view of json.

You can also use one of the online-viewers (http://jsonviewer.stack.hu/ , https://jsoneditoronline.org/) which look nice, but I wouldn’t recommend this if your data are sensitive in terms of privacy.

answered May 6, 2019 at 11:59

Cmd.Spock's user avatar

For Safari 12 and later, you can try the JSONBeautifier bookmarklet. Also works with other browsers.

I created this because JSON Formatter for Safari stopped working in Safari 12. There are a few new options for Safari 12, but I didn’t find an open source one in the App Store, and I do not trust closed source browser extensions.

This can be used as a bookmarklet or the source, json-beautifier.js, can be copied and pasted into the browser console. The code is freely available for review and is less than 100 lines of code including comments. Runs entirely on your device and never sends your data over a network.

Works with local files too. 🤓

answered Jul 23, 2020 at 2:17

Keith Shaw's user avatar

Keith ShawKeith Shaw

6246 silver badges7 bronze badges

answered May 6, 2022 at 4:39

akaJes's user avatar

0

Right click on JSON file, select open, navigate to program you want open with(notepad). Consecutive opens automatically use notepad.

answered Apr 4, 2013 at 12:33

Justin's user avatar

JsonDiscovery

A browser extension that changes the way you’re viewing JSON

Chrome Web Store
Mozilla Addons

JsonDiscovery

Add the extension to your browser:

  • Chrome Web Store (for Chrome & Edge, see additional instructions)
  • Firefox Browser Add-ons (see additional instructions)
  • Releases section

JsonDiscovery is based on Discovery.js which provides powerful features for rapid JSON analysis and beautiful reports on the fly!

Most exciting features:

  • Show JSON as an interactive tree with highlighting
  • Easy an object or an array copy to clipboard
  • Data structure signature (like in TypeScript)
  • Data transformation with a query using Jora, suggestions on a query typing
  • Customisation of JSON data presentation (using tables, lists and so on)
  • Custom data presentation (a report) sharing by a link
  • Works on any page with a valid JSON – URL/content type doesn’t matter (might not work for urls with strict CSP in some cases)
  • Works on local files (see instructions for Chromium browsers below)
  • Works offline (doesn’t perform any network requests)

Read more on Medium

Additional instructions

Chrome & Edge

By default installed extensions in Chromium browsers doesn’t work in Incognito mode and has no access to local files. If you need these features, then you should enable it:

  • Head to chrome://extensions
  • Find JsonDiscovery
  • Click Details button
  • Enable Allow in Incognito to make JsonDiscovery work in Incognito mode
  • Enable Allow access to file URLs to make JsonDiscovery work for local files

Firefox

To make JsonDiscovery work in Firefox you should disable default JSON viewer:

  • Head to about:config
  • Search for devtools.jsonview.enabled setting
  • Toggle the setting to false

Development

Clone the repository, run npm install and start local development server with npm run dev command.

Add dev version of the extension to your browser:

  • Chromium browsers (Chrome, Edge)

    • Head to chrome://extensions/
    • Click Developer mode in the top right corner
    • Click Load unpacked
    • Select a folder with extension source files (build-chrome)
  • Firefox

    • Head to about:debugging
    • Click Load Temporary Add-on
    • Find the folder with extension source files (build-firefox) and select manifest.json file

Do you work with AJAX requests a lot and need to quickly check URLs for JSON results? Then you probably know that it’s a fairly big hassle to examine JSON results directly in the browser. Yes, you can use FireBug or Fiddler which work pretty well for actual AJAX requests, but if you just fire off a URL for quick testing in the browser you usually get hit by the Save As dialog and the download manager, followed by having to open the saved document in a text editor in FireFox.

Enter JSONView which allows you to simply display JSON results directly in the browser. For example, imagine I have a URL like this:

http://localhost/westwindwebtoolkitweb/RestService.ashx?Method=ReturnObject&format=json&Name1=Rick&Name2=John&date=12/30/2010

typed directly into the browser and that that returns a complex JSON object. With JSONView the result looks like this:

JsonViewBrowser

No fuss, no muss. It just works. Here the result is an array of Person objects that contain additional address child objects displayed right in the browser.

JSONView basically adds content type checking for application/json results and when it finds a JSON result takes over the rendering and formats the display in the browser. Note that it re-formats the raw JSON as well for a nicer display view along with collapsible regions for objects. You can still use View Source to see the raw JSON string returned.

For me this is a huge time-saver. As I work with AJAX result data using GET and REST style URLs quite a bit it’s a big timesaver. To quickly and easily display JSON is a key feature in my development day and JSONView for all its simplicity fits that bill for me. If you’re doing AJAX development and you often review URL based JSON results do yourself a favor and pick up a copy of JSONView.

Other Browsers

JSONView works only with FireFox – what about other browsers?

Chrome
Chrome actually displays raw JSON responses as plain text without any plug-ins. There’s no plug-in or configuration needed, it just works, although you won’t get any fancy formatting.

[updated from comments]
There’s also a port of JSONView available for Chrome from here:

https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc

It looks like it works just about the same as the JSONView plug-in for FireFox. Thanks for all that pointed this out…

Internet Explorer
Internet Explorer probably has the worst response to JSON encoded content: It displays an error page as it apparently tries to render JSON as XML:

IeJson

Yeah that seems real smart – rendering JSON as an XML document. WTF? To get at the actual JSON output, you can use View Source.

To get IE to display JSON directly as text you can add a Mime type mapping in the registry:

 JsonRegistry

Create a new application/json key in:

  • HKEY_CLASSES_ROOTMIMEDatabaseContentTypeapplication/json

  • Add a string value of CLSID with a value of {25336920-03F9-11cf-8FD0-00AA00686F13}

  • Add a DWORD value of Encoding with a value of 80000

I can’t take credit for this tip – found it here first on Sky Sander’s Blog. Note that the CLSID can be used for just about any type of text data you want to display as plain text in the IE. It’s the in-place display mechanism and it should work for most text content. For example it might also be useful for looking at CSS and JS files inside of the browser instead of downloading those documents as well.

Do you want to query JSON document, extract data, select sub sections or testing a query quickly? This articles explains to do it using Chrome Developer tools. I am using Google Chrome Version 60.0.3112.113. But it should work for all recent versions.

Read Also:
Copy DropDownList Data from a Website: Chrome Developer Tools

Video:

Here is demo video to show how to inspect JSON and extract data:

Steps:

1. Store As Global variable

It is easy to capture json web response in Network tab. Right click on the JSON object and select the ‘Store as Global Variable‘ option which is going to create a variable tempX where X is going to be an integer (temp1, temp2 so on and so forth).


2. Ctrl + Alt + click on arrow to auto expand object

To expand node and all its children, press Ctrl + Alt + click. Basically, we are going to search in JSON but it is available in visible content that’s why we are expanding all nodes.

3. Search in JSON object

Ctrl + F to open search box, enter term to search in JSON. It is easy to get properties, we want to pick.

4. Copy property path

May be searched data at Nth level of hierarchy, so right click on property and click “Copy Property Path“.

For verification, open console, type the temp variable and paste the property path, you must get the expected result.
Suppose the Global variable is “temp1” and copied property path is “[0].name” then the below expression should return the expected result

temp1[0].name 

5. Code to extract data in console

Chrome developer tools supports ES6 arrow functions so we are going to use it with array map function

To get list of all names

temp1.map(function(i) {return i.name; })

or

temp1.map((i) => { return i.name})

or

temp1.map(i => i.name)

all will return the same result.

Let’s pick name and screen_name properties in tabular format:

console.table(temp1.map((j) => { return { name : j.name, screenName : j.screen_name}}))

Conclusion:

In this article, we saw how easy is to query JSON object and extract data in Chrome Developer Tools. Also, explored “Store as Global Variable” and “Copy property path” features. Hope, it saves your bunch of time.

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Ошибка в декларации по ндс как исправить ошибку
  • Как найти уникальное число в массиве java
  • Зная площадь как найти стороны прямоугольника если
  • Как найти работу автослесарем без опыта
  • Как исправить соединение с сетью дота 2

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии