1 | # json-from-script
|
2 |
|
3 | Tiny _222b_ JSON parser for your [Content Security Policy](https://developers.google.com/web/fundamentals/security/csp/) aware script tags.
|
4 |
|
5 | [![NPM version](https://img.shields.io/npm/v/json-from-script.svg)](https://www.npmjs.com/package/json-from-script)
|
6 | [![Build Status](https://travis-ci.org/robinvdvleuten/json-from-script.svg?branch=master)](https://travis-ci.org/robinvdvleuten/json-from-script)
|
7 |
|
8 | ## Installation
|
9 |
|
10 | ```
|
11 | $ npm i json-from-script --save
|
12 |
|
13 | or
|
14 |
|
15 | $ yarn add json-from-script
|
16 | ```
|
17 |
|
18 | ## Usage
|
19 |
|
20 | [**Real Example on JSFiddle**](https://jsfiddle.net/robinvdvleuten/9jk7L3vx/) ➡️
|
21 |
|
22 | When your HTML contains any script tag like this;
|
23 |
|
24 | ```html
|
25 | <script type="application/json" class="data" data-attribute="foo">{"bar":"baz"}</script>
|
26 | ```
|
27 |
|
28 | You can parse it in your Javascript application like this;
|
29 |
|
30 | ```js
|
31 | import jsonFromScript from 'json-from-script';
|
32 |
|
33 | // Parsed will be { foo: { bar: 'baz' } }
|
34 | const parsed = jsonFromScript();
|
35 | ```
|
36 |
|
37 | ## API
|
38 |
|
39 | ### `jsonFromScript(className, attribute)`
|
40 |
|
41 | Creates a new instance of the parser with the given options. The following options
|
42 | can alternatively be provided to configure the parser for your specific needs:
|
43 |
|
44 | - `className <String>`: The class name of the script tags to parse. (default: __data__)
|
45 | - `attribute <String>`: The data attribute to use when setting the attribute on the parsed object. (default: __attribute__)
|
46 |
|
47 | ## License
|
48 |
|
49 | MIT © [Robin van der Vleuten](https://www.robinvdvleuten.nl)
|