├── .eslintrc.json ├── .gitignore ├── README.md ├── components ├── Bottom.js ├── JSONStringifier.js ├── Layout.js ├── Top.js ├── jsonlint.js └── xmltojson.js ├── contexts └── ValidContext.js ├── hooks ├── useAdBlockCheck.js └── useExtensionCheck.js ├── jsconfig.json ├── license.txt ├── markdown ├── benefits-of-using-a-json-beautifier.md ├── common-mistakes-in-json-and-how-to-avoid-them.md ├── datasets │ ├── emoticons.md │ ├── programming-languages.md │ └── us-states-with-detail.md ├── how-to-open-json-file.md ├── json-parse.md ├── json-stringify-guide.md ├── mastering-json-format.md ├── mastering-json-in-javascript.md └── privacy.md ├── next.config.js ├── package-lock.json ├── package.json ├── pages ├── [...slug] │ └── index.js ├── _app.js ├── index.js ├── json-formatter.js ├── json-stringify.js └── xml-to-json.js ├── postcss.config.js ├── public ├── browserconfig.xml ├── datasets │ ├── emoticons.json │ ├── programming-languages.json │ ├── sample.json │ └── us-states-with-detail.json ├── favicon.ico ├── fonts │ ├── MonoLisaVariableItalic.woff2 │ └── MonoLisaVariableNormal.woff2 ├── images │ ├── android-chrome-192x192.png │ ├── android-chrome-512x512.png │ ├── apple-touch-icon.png │ ├── chrome.svg │ ├── favicon-16x16.png │ ├── favicon-32x32.png │ ├── formatter │ │ ├── 1.png │ │ ├── 2.png │ │ ├── 3.png │ │ └── 4.png │ ├── logo.png │ ├── logo.svg │ ├── mstile-150x150.png │ ├── safari-pinned-tab.svg │ └── site.webmanifest └── robots.txt ├── styles └── globals.css ├── tailwind.config.js └── vercel.json /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "next/core-web-vitals" 3 | } 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # next.js 12 | /.next/ 13 | /out/ 14 | 15 | # production 16 | /build 17 | 18 | # misc 19 | .DS_Store 20 | *.pem 21 | 22 | # debug 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | 27 | # local env files 28 | .env 29 | .env.local 30 | .env.development.local 31 | .env.test.local 32 | .env.production.local 33 | 34 | # vercel 35 | .vercel 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JSONLint.com 2 | 3 | ## Overview 4 | 5 | [**JSONLint**](https://jsonlint.com) is your go-to online solution for JSON data validation and formatting. Whether you are debugging a system, or just need to ensure your JSON data is in the correct format, JSONLint is here to assist. 6 | 7 | > [!NOTE] 8 | > We also recommend checking out our [JSON Formatter Google Chrome plugin](https://chrome.google.com/webstore/detail/json-formatter/ondecobpcidaehknoegeapmclapnkgcl) ([GitHub Repo](https://github.com/circlecell/jsonformatter)) 9 | 10 | ## Features 11 | 12 | - **JSON Validation**: Instantly verify if your JSON data is correctly formatted. Get precise error details for any discrepancies. 13 | - **JSON Beautification**: Transform your JSON data into a human-friendly format, making it effortlessly readable and editable. 14 | - **Lightweight & Fast**: Designed for efficiency, ensuring you get the results you need instantly. 15 | 16 | ## How to Use 17 | 18 | 1. Visit [JSONLint.com](https://jsonlint.com/) 19 | 2. Paste JSON data. 20 | 3. Click on the 'Validate JSON' button. 21 | 4. Review results. If there are issues, JSONLint will highlight them and suggest corrections. 22 | 23 | ## Feedback & Contributions 24 | 25 | We are always looking to make JSONLint even better! If you have any suggestions, features requests, or found a bug, please: 26 | 27 | - [Create an Issue](https://github.com/circlecell/jsonlint/issues) or 28 | - [Submit a Pull Request](https://github.com/circlecell/jsonlint/pulls) 29 | -------------------------------------------------------------------------------- /components/Bottom.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import Link from 'next/link' 3 | 4 | export default function Bottom() { 5 | 6 | return ( 7 | 68 | ) 69 | } 70 | -------------------------------------------------------------------------------- /components/JSONStringifier.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useRef } from 'react' 2 | import { Controlled as CodeMirror } from 'react-codemirror2' 3 | import copy from 'copy-to-clipboard' 4 | import 'codemirror/lib/codemirror.css' 5 | import 'codemirror/mode/javascript/javascript' 6 | 7 | // Fold 8 | import 'codemirror/addon/fold/foldcode' 9 | import 'codemirror/addon/fold/foldgutter' 10 | import 'codemirror/addon/fold/brace-fold' 11 | import 'codemirror/addon/fold/foldgutter.css' 12 | 13 | // Search 14 | import 'codemirror/addon/dialog/dialog.css' 15 | import 'codemirror/addon/search/matchesonscrollbar.css' 16 | import 'codemirror/addon/dialog/dialog' 17 | import 'codemirror/addon/search/searchcursor' 18 | import 'codemirror/addon/search/search' 19 | import 'codemirror/addon/scroll/annotatescrollbar' 20 | import 'codemirror/addon/search/matchesonscrollbar' 21 | import 'codemirror/addon/search/jump-to-line' 22 | 23 | const JSONStringifier = () => { 24 | const [jsonInput, setJsonInput] = useState('') 25 | const [stringifiedOutput, setStringifiedOutput] = useState('') 26 | const editorRef = useRef(null) 27 | const [copySuccess, setCopySuccess] = useState(false) 28 | 29 | const handleStringify = () => { 30 | if (!jsonInput.trim()) { 31 | setStringifiedOutput('Input field cannot be empty') 32 | return 33 | } 34 | 35 | try { 36 | const parsedJSON = JSON.parse(jsonInput) 37 | const standardStringified = JSON.stringify(parsedJSON) 38 | const escapedStringified = standardStringified.replace(/"/g, '\\"') 39 | setStringifiedOutput('"' + escapedStringified + '"') 40 | } catch (error) { 41 | setStringifiedOutput('Invalid JSON: ' + error.message) 42 | } 43 | } 44 | 45 | const handleClear = () => { 46 | if (editorRef.current) { 47 | editorRef.current.setValue('') 48 | setJsonInput('') 49 | setStringifiedOutput('') 50 | } 51 | // Check if the onClear callback from the parent component exists 52 | if (typeof onClear === 'function') { 53 | onClear() 54 | } 55 | } 56 | 57 | const handleCopy = () => { 58 | copy(stringifiedOutput) 59 | setCopySuccess(true) 60 | setTimeout(() => setCopySuccess(false), 2000) 61 | } 62 | 63 | return ( 64 |
65 |
66 |
67 | { 78 | setJsonInput(value); 79 | }} 80 | editorDidMount={editor => { editorRef.current = editor }} 81 | /> 82 |
83 | 84 | 85 | 86 |
87 |
88 | 100 | 125 |
126 |
127 | ) 128 | } 129 | 130 | export default JSONStringifier -------------------------------------------------------------------------------- /components/Layout.js: -------------------------------------------------------------------------------- 1 | import Top from './Top' 2 | import Bottom from './Bottom' 3 | 4 | export default function Layout({ children }) { 5 | return ( 6 | <> 7 | 8 |
{children}
9 | 10 | 11 | ) 12 | } -------------------------------------------------------------------------------- /components/Top.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect, useContext } from 'react' 2 | import { useRouter } from 'next/router' 3 | import Link from 'next/link' 4 | import Image from 'next/image' 5 | import ValidContext from '../contexts/ValidContext' 6 | 7 | export default function Top() { 8 | 9 | const router = useRouter() 10 | const [theme, setTheme] = useState('system') 11 | 12 | const { isValid } = useContext(ValidContext) 13 | 14 | const defaultPath = 'M18.5708 20C19.8328 20 20.8568 18.977 20.8568 17.714V13.143L21.9998 12L20.8568 10.857V6.286C20.8568 5.023 19.8338 4 18.5708 4M5.429 4C4.166 4 3.143 5.023 3.143 6.286V10.857L2 12L3.143 13.143V17.714C3.143 18.977 4.166 20 5.429 20M7.5 12H7.51M12 12H12.01M16.5 12H16.51M8 12C8 12.2761 7.77614 12.5 7.5 12.5C7.22386 12.5 7 12.2761 7 12C7 11.7239 7.22386 11.5 7.5 11.5C7.77614 11.5 8 11.7239 8 12ZM12.5 12C12.5 12.2761 12.2761 12.5 12 12.5C11.7239 12.5 11.5 12.2761 11.5 12C11.5 11.7239 11.7239 11.5 12 11.5C12.2761 11.5 12.5 11.7239 12.5 12ZM17 12C17 12.2761 16.7761 12.5 16.5 12.5C16.2239 12.5 16 12.2761 16 12C16 11.7239 16.2239 11.5 16.5 11.5C16.7761 11.5 17 11.7239 17 12Z' 15 | const validPath = 'M18.5708 20C19.8328 20 20.8568 18.977 20.8568 17.714V13.143L21.9998 12L20.8568 10.857V6.286C20.8568 5.023 19.8338 4 18.5708 4M5.429 4C4.166 4 3.143 5.023 3.143 6.286V10.857L2 12L3.143 13.143V17.714C3.143 18.977 4.166 20 5.429 20M7.5 12L9.93431 14.4343C10.1323 14.6323 10.2313 14.7313 10.3455 14.7684C10.4459 14.8011 10.5541 14.8011 10.6545 14.7684C10.7687 14.7313 10.8677 14.6323 11.0657 14.4343L16.5 9' 16 | const invalidPath = 'M18.5708 20C19.8328 20 20.8568 18.977 20.8568 17.714V13.143L21.9998 12L20.8568 10.857V6.286C20.8568 5.023 19.8338 4 18.5708 4M5.429 4C4.166 4 3.143 5.023 3.143 6.286V10.857L2 12L3.143 13.143V17.714C3.143 18.977 4.166 20 5.429 20M8 12H16' 17 | 18 | const getSystemTheme = () => { 19 | if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { 20 | return 'dark' 21 | } 22 | return 'light' 23 | } 24 | 25 | useEffect(() => { 26 | const storedTheme = localStorage.getItem('theme') 27 | if (storedTheme) { 28 | setTheme(storedTheme) 29 | } else { 30 | setTheme(getSystemTheme()) 31 | } 32 | }, []) 33 | 34 | useEffect(() => { 35 | if (theme === 'dark') { 36 | document.body.classList.add('dark') 37 | } else { 38 | document.body.classList.remove('dark') 39 | } 40 | }, [theme]) 41 | 42 | const toggleTheme = () => { 43 | if (theme === 'light' || theme === 'system') { 44 | setTheme('dark') 45 | localStorage.setItem('theme', 'dark') 46 | document.body.classList.add('dark') 47 | } else { 48 | setTheme('light') 49 | localStorage.setItem('theme', 'light') 50 | document.body.classList.remove('dark') 51 | } 52 | } 53 | 54 | return ( 55 | <> 56 |
57 | 107 |
108 | 109 | ) 110 | } -------------------------------------------------------------------------------- /components/jsonlint.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect, useRef, useContext } from 'react' 2 | import ValidContext from '../contexts/ValidContext' 3 | import jsonlint from 'jsonlint-mod' 4 | import copy from 'copy-to-clipboard' 5 | import { Controlled as CodeMirror } from 'react-codemirror2' 6 | import 'codemirror/lib/codemirror.css' 7 | import 'codemirror/mode/javascript/javascript' 8 | 9 | // Fold 10 | import 'codemirror/addon/fold/foldcode' 11 | import 'codemirror/addon/fold/foldgutter' 12 | import 'codemirror/addon/fold/brace-fold' 13 | import 'codemirror/addon/fold/foldgutter.css' 14 | 15 | // Search 16 | import 'codemirror/addon/dialog/dialog.css' 17 | import 'codemirror/addon/search/matchesonscrollbar.css' 18 | import 'codemirror/addon/dialog/dialog' 19 | import 'codemirror/addon/search/searchcursor' 20 | import 'codemirror/addon/search/search' 21 | import 'codemirror/addon/scroll/annotatescrollbar' 22 | import 'codemirror/addon/search/matchesonscrollbar' 23 | import 'codemirror/addon/search/jump-to-line' 24 | 25 | function customStringify(jsonObject, pretty) { 26 | let jsonString = pretty ? JSON.stringify(jsonObject, null, 4) : JSON.stringify(jsonObject) 27 | jsonString = jsonString.replace(/\\\\u([\da-fA-F]{4})/g, '\\u$1').replace(/\\\//g, '/') 28 | 29 | return jsonString 30 | } 31 | 32 | function convertSpacesToTabs(str, spacesPerIndent) { 33 | const spaceGroup = ' '.repeat(spacesPerIndent) 34 | return str.split('\n').map(line => line.replace(new RegExp(`^(${spaceGroup})+`, 'g'), match => '\t'.repeat(match.length / spacesPerIndent))).join('\n') 35 | } 36 | 37 | function customCompress(jsonString) { 38 | let modifiedString = jsonString.replace(/\\u([\da-fA-F]{4})/g, 'UNICODE_$1') 39 | .replace(/\\\//g, 'SLASH') 40 | try { 41 | let compressedJson = JSON.stringify(JSON.parse(modifiedString)) 42 | compressedJson = compressedJson.replace(/UNICODE_([\da-fA-F]{4})/g, '\\u$1') 43 | .replace(/SLASH/g, '\\/') 44 | 45 | return compressedJson 46 | } catch (error) { 47 | console.error("Error in customCompress:", error) 48 | return jsonString 49 | } 50 | } 51 | 52 | const JSONLint = ({ json, url, onClear }) => { 53 | const { isValid, setIsValid } = useContext(ValidContext) 54 | const [isPretty, setIsPretty] = useState(false) 55 | const [input, setInput] = useState('') 56 | const [output, setOutput] = useState('') 57 | const [error, setError] = useState('') 58 | const editorRef = useRef(null) 59 | const errorMarkerRef = useRef(null) 60 | const [copySuccess, setCopySuccess] = useState(false) 61 | 62 | const handleValidate = (jsonToValidate = input) => { 63 | if (errorMarkerRef.current) { 64 | errorMarkerRef.current.clear() 65 | errorMarkerRef.current = null 66 | } 67 | 68 | try { 69 | const parsed = jsonlint.parse(jsonToValidate) 70 | const indentedJson = customStringify(parsed, true) 71 | setOutput(indentedJson) 72 | setInput(indentedJson) 73 | setError('') 74 | setIsValid(true) 75 | document.body.classList.add('valid') 76 | document.body.classList.remove('invalid') 77 | } catch (e) { 78 | setOutput('') 79 | setError(e.toString()) 80 | setIsValid(false) 81 | document.body.classList.add('invalid') 82 | document.body.classList.remove('valid') 83 | const match = e.toString().match(/line (\d+)/) 84 | if (match) { 85 | const lineNumber = parseInt(match[1], 10) - 1 86 | errorMarkerRef.current = editorRef.current.markText( 87 | { line: lineNumber, ch: 0 }, 88 | { line: lineNumber + 1, ch: 0 }, 89 | { className: 'cm-error-highlight' } 90 | ) 91 | } 92 | } 93 | } 94 | 95 | const handleFormatting = () => { 96 | try { 97 | let formattedJson 98 | if (isPretty) { 99 | formattedJson = customStringify(jsonlint.parse(input), true) 100 | formattedJson = convertSpacesToTabs(formattedJson, 4) 101 | } else { 102 | formattedJson = customCompress(input) 103 | } 104 | setInput(formattedJson) 105 | setIsPretty(!isPretty) 106 | } catch (error) { 107 | setError(`Failed to format JSON: ${error.message}`) 108 | } 109 | } 110 | 111 | const handleClear = () => { 112 | if (editorRef.current) { 113 | editorRef.current.setValue('') 114 | setInput('') 115 | setError('') 116 | setOutput('') 117 | setIsValid(null) 118 | document.body.classList.remove('valid', 'invalid') 119 | } 120 | // Check if the onClear callback from the parent component exists 121 | if (typeof onClear === 'function') { 122 | onClear() 123 | } 124 | } 125 | 126 | const handleCopy = () => { 127 | copy(input) 128 | setCopySuccess(true) 129 | setTimeout(() => setCopySuccess(false), 2000) 130 | } 131 | 132 | useEffect(() => { 133 | if (json) { 134 | const decodedJson = decodeURIComponent(json) 135 | setInput(decodedJson) 136 | setTimeout(() => handleValidate(decodedJson), 0) 137 | } else if (url) { 138 | fetch(decodeURIComponent(url)) 139 | .then(response => response.json()) 140 | .then(data => { 141 | const fetchedJson = JSON.stringify(data, null, 4) 142 | setInput(fetchedJson) 143 | setTimeout(() => handleValidate(fetchedJson), 0) 144 | }) 145 | .catch(error => { 146 | setError(`Failed to fetch JSON from URL: ${error.message}`) 147 | setIsValid(false) 148 | }) 149 | } 150 | }, [json, url]) 151 | 152 | return ( 153 | <> 154 |
155 | { 168 | editorRef.current = editor 169 | }} 170 | onBeforeChange={(editor, data, value) => { 171 | setInput(value) 172 | }} 173 | /> 174 | 199 |
200 |
201 | 202 | 203 | 204 | 205 | {isValid === true && 206 |
207 | JSON is valid! 208 |
209 | } 210 | 211 | {isValid === false && 212 |
213 | Invalid JSON! 214 | {error && 215 |
216 | 							{error}
217 | 						
218 | } 219 |
220 | } 221 | 222 |
223 | 224 | ) 225 | } 226 | 227 | export default JSONLint -------------------------------------------------------------------------------- /components/xmltojson.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useContext } from 'react' 2 | import { parseString } from 'xml2js' 3 | import JSONLint from './jsonlint' 4 | import { Controlled as CodeMirror } from 'react-codemirror2' 5 | import 'codemirror/lib/codemirror.css' 6 | import 'codemirror/mode/xml/xml' 7 | 8 | // Fold 9 | import 'codemirror/addon/fold/foldcode' 10 | import 'codemirror/addon/fold/foldgutter' 11 | import 'codemirror/addon/fold/brace-fold' 12 | import 'codemirror/addon/fold/foldgutter.css' 13 | 14 | // Search 15 | import 'codemirror/addon/dialog/dialog.css' 16 | import 'codemirror/addon/search/matchesonscrollbar.css' 17 | import 'codemirror/addon/dialog/dialog' 18 | import 'codemirror/addon/search/searchcursor' 19 | import 'codemirror/addon/search/search' 20 | import 'codemirror/addon/scroll/annotatescrollbar' 21 | import 'codemirror/addon/search/matchesonscrollbar' 22 | import 'codemirror/addon/search/jump-to-line' 23 | 24 | const XMLtoJSONLint = () => { 25 | const [xmlInput, setXmlInput] = useState('') 26 | const [jsonOutput, setJsonOutput] = useState('') 27 | const [error, setError] = useState(null) 28 | const [isValid, setIsValid] = useState(null) 29 | 30 | const handleConvert = () => { 31 | if (!xmlInput.trim()) { 32 | setError('XML field cannot be empty') 33 | setIsValid(false) 34 | return 35 | } 36 | 37 | parseString(xmlInput, (err, result) => { 38 | if (err) { 39 | setError(err.message) 40 | setIsValid(false) 41 | return 42 | } 43 | const jsonString = JSON.stringify(result, null, 4) 44 | setJsonOutput(jsonString) 45 | setError(null) 46 | setIsValid(true) 47 | }) 48 | } 49 | 50 | const handleClear = () => { 51 | setJsonOutput('') 52 | setError(null) 53 | setIsValid(null) 54 | } 55 | 56 | return ( 57 |
58 | 59 |
60 |
61 |
62 | { 73 | setXmlInput(value) 74 | }} 75 | /> 76 |
77 | 78 | 79 | 80 |
81 |
82 | 83 |
84 |
85 | 86 | {isValid === false && 87 |
88 | Invalid XML! 89 | {error && 90 |
 91 | 							{error}
 92 | 						
93 | } 94 |
95 | } 96 |
97 | ) 98 | } 99 | 100 | export default XMLtoJSONLint 101 | -------------------------------------------------------------------------------- /contexts/ValidContext.js: -------------------------------------------------------------------------------- 1 | import { createContext } from 'react' 2 | 3 | const ValidContext = createContext({ 4 | isValid: null, 5 | setIsValid: () => {} 6 | }) 7 | 8 | export default ValidContext -------------------------------------------------------------------------------- /hooks/useAdBlockCheck.js: -------------------------------------------------------------------------------- 1 | // hooks/useAdBlockCheck.js 2 | 3 | 4 | import { useEffect, useState } from 'react'; 5 | 6 | const useAdBlockCheck = () => { 7 | const [hasAdBlocker, setHasAdBlocker] = useState(null); 8 | 9 | useEffect(() => { 10 | const checkIfUserIsBlockingAdsAsync = (() => { 11 | let adBlockDetected; 12 | 13 | return () => { 14 | if (typeof adBlockDetected !== 'undefined') { 15 | return Promise.resolve(adBlockDetected); 16 | } 17 | 18 | const url = 'https://tpc.googlesyndication.com/pagead/images/adchoices/en.png'; 19 | 20 | return fetch(url, { mode: 'no-cors' }) 21 | .then(() => { 22 | adBlockDetected = false; 23 | }) 24 | .catch(() => { 25 | adBlockDetected = true; 26 | }) 27 | .then(() => { 28 | setHasAdBlocker(adBlockDetected); 29 | return adBlockDetected; 30 | }); 31 | }; 32 | })(); 33 | 34 | checkIfUserIsBlockingAdsAsync(); 35 | }, []); 36 | 37 | return hasAdBlocker; 38 | }; 39 | 40 | export default useAdBlockCheck; 41 | 42 | -------------------------------------------------------------------------------- /hooks/useExtensionCheck.js: -------------------------------------------------------------------------------- 1 | // hooks/useExtensionCheck.js 2 | 3 | import { useEffect, useState, useRef } from 'react'; 4 | 5 | const useExtensionCheck = () => { 6 | const [isExtensionInstalled, setIsExtensionInstalled] = useState(null); 7 | const extensionTimeoutRef = useRef(null); 8 | 9 | useEffect(() => { 10 | const checkExtension = () => { 11 | const handleMessage = (event) => { 12 | if (event.data === 'extensionInstalled') { 13 | setIsExtensionInstalled(true); 14 | window.removeEventListener('message', handleMessage); 15 | clearTimeout(extensionTimeoutRef.current); 16 | } 17 | }; 18 | 19 | window.addEventListener('message', handleMessage); 20 | 21 | extensionTimeoutRef.current = setTimeout(() => { 22 | window.postMessage('isExtensionInstalled', '*'); 23 | }, 100); 24 | 25 | // Fallback to assume the extension is not installed if no message is received 26 | setTimeout(() => { 27 | window.removeEventListener('message', handleMessage); 28 | setIsExtensionInstalled(false); 29 | }, 500); 30 | }; 31 | 32 | checkExtension(); 33 | 34 | return () => { 35 | if (extensionTimeoutRef.current) { 36 | clearTimeout(extensionTimeoutRef.current); 37 | } 38 | }; 39 | }, []); 40 | 41 | return isExtensionInstalled; 42 | }; 43 | 44 | export default useExtensionCheck; 45 | -------------------------------------------------------------------------------- /jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "paths": { 5 | "@/*": ["./*"] 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2025 Todd Garland 2 | 3 | MIT License 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | "Software"), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 20 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 22 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /markdown/benefits-of-using-a-json-beautifier.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Benefits of Using a JSON Beautifier" 3 | description: "Utilizing a JSON beautifier can vastly improve readability, making it easier to comprehend and navigate through even the most complex JSON data." 4 | --- 5 | 6 | # Boost Your Efficiency: Understanding the Benefits of Using a JSON Beautifier 7 | 8 | ## Why use a JSON Beautifier? 9 | 10 | As I delve deeper into the realms of JSON data management, I've realized a key factor that enhances my efficiency - employing a JSON beautifier. If you're working with JSON data, this tool can be your game changer. **A JSON beautifier** carries significant benefits for both developers and data analysts, and here's why. 11 | 12 | Firstly, it boosts readability. JSON data, when not formatted, can be highly complex and unorganized. The JSON beautifier steps in here, transforming unstructured data into well-formatted, neat text. It's like turning a pile of unsorted paperwork into neatly organized files, making it significantly easier to understand and interpret data. 13 | 14 | Understanding JSON data structures is yet another advantage. Undeniably, JSON's structural complexity can challenge even the most experienced developers. A **JSON beautifier** serves as a thoughtful assistant, helping you comprehend intricate data structures with ease. By organizing data into a more comprehensive pattern, it unfolds the complex JSON frameworks right in front of your eyes. 15 | 16 | Spotting errors is seamless with a JSON beautifier. In the extensive world of JSON data, even a minute error can cause significant downfalls. The JSON beautifier sheds light on such hidden inaccuracies, projecting the error right on your screen. Its structured formatting enables you to quickly spot any discrepancies, saving your precious time and resources. 17 | 18 | In an increasingly digital world where JSON data reigns, implementing a JSON beautifier in your workflow is smart. So, the next time you're struggling with JSON data, know that the JSON beautifier has got your back. With it at your disposal, you'll find working with JSON data as easy as pie. So, don't hold back. Let it simplify your JSON adventures and give your efficiency a solid boost. 19 | 20 | ## Benefits of Using a JSON Beautifier 21 | 22 | Let's dive straight into the many benefits of using a JSON beautifier in your daily routines. First and foremost, **readability** is substantially improved when using a JSON beautifier. This tool transforms the cluttered, hard-to-follow raw JSON data into a neat, orderly structure. We're no longer forced to squint our eyes and decipher strings of data that may look like an alien language. It's a simple concept—organized data is easier to read, understand, and analyze. 23 | 24 | The beautifier also allows us to **grasp complex data structures** more readily. Picture trying to make sense of a JSON data array comprising ten, twenty, or fifty elements—it's like trying to find a needle in a haystack. But guess what? With a JSON beautifier, it's no longer an arduous task. The tool neatly arranges the elements, removing the unnecessary autograph to showcase the clear hierarchy. It's a real game-changer! 25 | 26 | Another significant advantage is the tool's ability to **identify errors rapidly**. When dealing with JSON, errors like a missing bracket or a misplaced comma can sabotage the entire data structure. Using the beautifier's precision and efficacy, these errors become glaringly obvious. We can complete our debugging process in no time, becoming more efficient at handling JSON data. 27 | 28 | Jumping onto the JSON beautifier bandwagon can save us significant time and effort. It minimizes the chances of misinterpretation, hitches less on confusion, and boosts our productivity dramatically. There's little to no learning curve involved, yet the rewards are exceptional. So why not harness the power that a JSON beautifier extends and sail smoothly in the realm of JSON data? Yes, I'm talking about reducing stress and elevating proficiency! 29 | 30 | It's becoming more evident that integrating a JSON beautifier into our workflow is an absolute must. It’s clearly a win-win situation. Now that we understand the benefits, let's move onto understanding its unique functionalities in the next section. 31 | 32 | ## Understanding JSON Data Structures 33 | 34 | Understanding JSON, or JavaScript Object Notation, data structures is like solving a significant part of the web data handling puzzle. This lightweight data interchange format is easy for humans to read and write and for machines to parse and generate. It's a text format that's completely language independent but uses conventions familiar to programmers. 35 | 36 | JSON's basic data structures include objects and arrays. An **object** is an unordered collection of zero or more name/value pairs, where a name is a string, and a value is a string, number, Boolean expression, null, object, or array. Objects are enclosed within braces `{}` and the name/value pairs are separated by commas. 37 | 38 | Let's explore an example of a JSON object: 39 | 40 | ``` 41 | { 42 | "name": "John", 43 | "age": 30, 44 | "city": "New York" 45 | } 46 | ``` 47 | 48 | In the above example, `name`, `age`, and `city` are names, and `"John"`, `30`, and `"New York"` are their corresponding values. 49 | 50 | An **array**, on the other hand, is an ordered collection of values. Arrays are enclosed within square brackets `[]` and the values are separated by commas. An array value can be a string, number, Boolean expression, null, object, or even another array. 51 | 52 | Take a look at a JSON array example: 53 | 54 | ``` 55 | { 56 | "employees": ["John", "Anna", "Peter"] 57 | } 58 | ``` 59 | 60 | In this case, the `employees` name corresponds to an array of strings. 61 | 62 | Utilizing a JSON beautifier to view these structures can vastly improve readability, making it easier to comprehend and navigate through even the most complex JSON data. 63 | 64 | ## Spotting Errors with a JSON Beautifier 65 | 66 | One of the **major merits** of using a JSON beautifier in my workflow is its ability to spot errors swiftly. I've often found JSON data very intricate and packed with data. It can become an uphill task to debug if something goes amiss. This is where a JSON beautifier steps in, becoming my trusted ally. 67 | 68 | It's worth noting, JSON works on key-value pairs and follows strict syntax rules. Even a small misstep, like a missing comma or an unclosed bracket, can lead to errors that disturb the data flow. It can be quite a challenge to locate these small yet significant errors manually in densely packed JSON structures. That's where the JSON beautifier shows its brilliance. It **effectively spots errors**, large or small, refining the debugging process. 69 | 70 | Using a JSON beautifier tool, I can transform the complex data into a well-structured and highly readable format. Every bracket, every key, and every value gets its own space, making the structure noticeably clear. Errors, then, become easier to spot. 71 | 72 | Let me share an experience with you. I remember working on a JSON file with thousands of lines of code. Spotting errors literally felt like looking for a needle in a haystack. But once I opted for a JSON beautifier, it highlighted the line numbers of syntax errors. It saved me a substantial amount of time and hassle. So for any professional working with JSON data regularly, integrating a JSON beautifier into their workflow can make a world of difference. 73 | 74 | In the next section, I'll delve deeper into how a JSON beautifier aids in understanding complex data structures. We'll also touch upon some examples worth noting. 75 | 76 | ## Improving Workflow with a JSON Beautifier 77 | 78 | Optimizing your workflow with a **JSON beautifier** is a game changer. The power it brings to managing and understanding JSON data simplifies tasks immensely, making it a vital tool for developers and data analysts alike. 79 | 80 | As a seasoned developer, I can't stress enough the value of readability when dealing with data. Processing raw, disorganized JSON data can be a nightmare, and it's where a JSON beautifier comes into play. It neatly formats the data, outlining its structure clearly. That's when working with JSON becomes a breeze; all the cryptic, confusing lines of text transform into an easy-to-navigate data structure. 81 | 82 | This organizational clarity isn't the only benefit, though. The beautifier can also act as the first line of defense in error detection, which is a considerable part of my day-to-day work. Syntax errors, missing elements or incorrectly inserted values - the JSON beautifier identifies and highlights all these errors. It's like having a guardian angel on your shoulder, pointing out the pitfalls before you unknowingly step into them. 83 | 84 | The efficiency a JSON beautifier provides extends even to complex data structures. In the early days of my career, I'd struggle with convoluted, multi-level JSON arrays and objects. The beautifier, however, simplifies them significantly. It's like a tour guide leading you through a labyrinth, ensuring you don't get lost in the intricacies of your data. 85 | 86 | It's important to note that JSON beautifiers come in various types and complexities. Some offer basic formatting features, while others provide extensive customization and analysis capabilities. Understanding the needs of your projects and selecting the right JSON beautifier to meet those needs is critical in effectively managing JSON data. 87 | 88 | Remember, JSON beautifiers don't just improve readability, identification of errors, and understanding complex data structures - they are avenues to enhancing your data management workflow, boosting your efficiency and productivity. 89 | 90 | ## Conclusion 91 | 92 | So, we've seen how a JSON beautifier can be a game-changer in managing JSON data. It's not just about making data look pretty, but about improving efficiency and comprehension. With a JSON beautifier, you're not just reading data, you're understanding it. It's your first line of defense against errors, quickly highlighting any issues and saving you valuable time. And when it comes to complex data structures, a JSON beautifier is your guide, making navigation a breeze. Remember, the right tool can make all the difference. So, choose your JSON beautifier wisely. It's time to elevate your data management game. Embrace the power of a JSON beautifier and experience the difference it can make. -------------------------------------------------------------------------------- /markdown/common-mistakes-in-json-and-how-to-avoid-them.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Common JSON Mistakes and How to Avoid Them" 3 | description: "Avoid common mistakes. See tooling options such as JSONLint - the trusted validator and reformatter for error-free code." 4 | --- 5 | 6 | # Common JSON Mistakes and How to Avoid Them 7 | 8 | ## Introduction 9 | 10 | JSON, short for JavaScript Object Notation, is a widely used open-standard format for representing structured data in a human-readable and compact manner. It enables the interchange of complex data structures between systems and has a diverse range of applications. Although it resembles readable text, not all systems use it for data communication. 11 | 12 | Furthermore, it's advisable to be aware of some common mistakes that occur when working with this format. We'll explore these mistakes and provide tips on how to avoid them. Even though, we'll mostly rely on tooling to detect and correct these mishaps, having a solid understanding of how they happen is a valuable prerequisite. 13 | 14 | 15 | ## Inconsistent Key Naming Conventions 16 | 17 | One such common mistake is the inconsistent use of key naming conventions. JSON keys should follow a consistent naming pattern throughout your code, such as **camelCase**, **snake_case**, or **kebab-case**. Mixing different naming conventions can lead to confusion and negatively impact readability and maintenance. 18 | 19 | #### A Bad Example 20 | 21 | 22 | ```json 23 | { 24 | "firstName": "Douglas", 25 | "last_name": "Crockford", 26 | "email-address": "doug.mock@example.com" 27 | } 28 | ``` 29 | 30 | #### The Proper Approach 31 | 32 | Choose a consistent naming convention for your JSON keys and stick to it. For instance, you might decide to use **camelCase** for all keys. 33 | 34 | ```json 35 | { 36 | "firstName": "Douglas", 37 | "lastName": "Crockford", 38 | "emailAddress": "doug.mock@example.com" 39 | } 40 | ``` 41 | 42 | 43 | ## Missing or Extra Commas 44 | 45 | Another potential mishap is forgetting to add a comma between elements or accidentally including an extra comma at the end of a list or object. In JSON, commas are used to separate elements within objects and arrays. A missing comma can cause a parsing error, while an extra comma is considered invalid syntax. 46 | 47 | #### A Bad Example 48 | 49 | ```json 50 | { 51 | "name": "Tim", 52 | "age": 29 53 | "city": "New York", 54 | "hobbies": ["reading", "traveling",] 55 | } 56 | ``` 57 | 58 | #### The Proper Approach 59 | 60 | To avoid this mistake, double-check your JSON code for any missing or extra commas. Ensure that each element within an object or array is followed by a comma, except for the last element. 61 | 62 | ```json 63 | { 64 | "name": "Tim", 65 | "age": 29, 66 | "city": "New York", 67 | "hobbies": ["reading", "traveling"] 68 | } 69 | ``` 70 | 71 | ## Improper Use of Quotes 72 | 73 | The creator of JSON was pretty strict when it comes to consistency. Keys and string values must be enclosed in double quotes **"**, while single quotes **'** aren't allowed. Using single quotes or improperly quoting keys and values can lead to parsing errors. 74 | 75 | 76 | #### A Bad Example 77 | 78 | ```json 79 | { 80 | 'title': 'Harry Potter and the Philosopher's Stone', 81 | "year": '1997', 82 | "author": ["J.K. Rowling"], 83 | } 84 | ``` 85 | 86 | #### The Proper Approach 87 | 88 | To fix this issue, make sure to use double quotes for all keys and string values. Additionally, be careful not to include quotes around numeric or boolean values, as this will change their data type to a string. 89 | 90 | ```json 91 | { 92 | "title": "Harry Potter and the Philosopher's Stone", 93 | "year": 1997, 94 | "author": ["J.K. Rowling"], 95 | "price": 15.99 96 | } 97 | ``` 98 | 99 | ## Mismatched Brackets and Braces 100 | 101 | Mismatched brackets(used for arrays) and braces (specific to objects), can lead to parsing errors in our code structures. It's crucial to have a corresponding closing bracket or brace for each opening one. 102 | 103 | #### A Bad Example 104 | 105 | ```json 106 | { 107 | "book": { 108 | "title": "The Lord of the Rings", 109 | "author": "J.R.R. Tolkien", 110 | "published_year": 1954, 111 | "characters": [ 112 | "Frodo Baggins", 113 | "Gandalf", 114 | "Samwise Gamgee", 115 | "Aragorn", 116 | "Legolas", 117 | "Gimli", 118 | "Boromir" 119 | ], 120 | } 121 | ``` 122 | 123 | #### The Proper Approach 124 | 125 | Carefully observe the nesting to ensure that all brackets and braces are correctly matched. In the above example, a closing brace is missing for the "book" object. 126 | 127 | ```json 128 | { 129 | "book": { 130 | "title": "The Lord of the Rings", 131 | "author": "J.R.R. Tolkien", 132 | "published_year": 1954, 133 | "characters": [ 134 | "Frodo Baggins", 135 | "Gandalf", 136 | "Samwise Gamgee", 137 | "Aragorn", 138 | "Legolas", 139 | "Gimli", 140 | "Boromir" 141 | ] 142 | } 143 | } 144 | ``` 145 | 146 | ## Invalid Data Types 147 | 148 | JSON structure with incorrect data types could lead to unexpected results and errors and bring confusion to an already attention-demanding workflow. Moreover, JSON has a limited set of data types: strings, numbers, booleans, objects, arrays, and null. So, make sure that you're using the correct data types for your keys and values. 149 | 150 | #### A Bad Example 151 | 152 | ```json 153 | { 154 | "name": "Bob", 155 | "age": "23", 156 | "isStudent": "false", 157 | "courses": { 158 | "math": 101, 159 | "history": "201" 160 | } 161 | } 162 | ``` 163 | 164 | #### The Proper Approach 165 | 166 | Review and correct any data type inconsistencies. As we can see in the mock example, the "age" and "isStudent" values should be a number and a boolean, respectively, and the "history" course number should be a number as well. 167 | 168 | ```json 169 | { 170 | "name": "Bob", 171 | "age": 23, 172 | "isStudent": false, 173 | "courses": { 174 | "math": 101, 175 | "history": 201 176 | } 177 | } 178 | ``` 179 | 180 | ## Incorrect Nesting of Objects and Arrays 181 | 182 | Improperly nested objects and arrays in JSON code can lead to parsing errors, negatively impacting the readability and maintainability of the structure. To avoid these issues, it's a must that objects and arrays are correctly nested. 183 | 184 | #### A Bad Example 185 | 186 | ```json 187 | { 188 | "team": { 189 | "name": "Dream Team", 190 | "members": [ 191 | "John", 192 | "Emma", 193 | "skills": { 194 | "John": ["Python", "JavaScript"], 195 | "Emma": ["Java", "C++"] 196 | } 197 | ] 198 | } 199 | } 200 | ``` 201 | 202 | #### The Proper Approach 203 | 204 | To prevent such errors, do meticulously reviews, and confirm that objects and arrays are nested in the right order. In the given example, the "skills" object must be placed outside the "members" array and nested correctly within the "team" object. 205 | 206 | ```json 207 | { 208 | "team": { 209 | "name": "Dream Team", 210 | "members": ["John", "Emma"], 211 | "skills": { 212 | "John": ["Python", "JavaScript"], 213 | "Emma": ["Java", "C++"] 214 | } 215 | } 216 | } 217 | ``` 218 | 219 | 220 | ## Trailing Decimal Point in Numbers 221 | 222 | JSON's possibilities allow for numbers to be represented in decimal, scientific, or integer notation. However, using a trailing decimal point without any digits following it is considered invalid syntax leading to parsing errors once again. 223 | 224 | 225 | #### A Bad Example 226 | 227 | ```json 228 | { 229 | "product": { 230 | "name": "Laptop", 231 | "price": 999., 232 | "weight": 1.5 233 | } 234 | } 235 | ``` 236 | #### The Proper Approach 237 | 238 | So, to avoid such errors, have at least one digit following the decimal point. In the example above, the "price" value should include a digit after the decimal point: 239 | 240 | ```json 241 | { 242 | "product": { 243 | "name": "Laptop", 244 | "price": 999.0, 245 | "weight": 1.5 246 | } 247 | } 248 | ``` 249 | 250 | ## Summary 251 | 252 | What we saw in the previous sections was tailored to showcase the common errors through mock examples. But, JSON data can be quite verbose, especially when dealing with large datasets. To improve storage and transmission efficiency, we can leverage JSON data compression, which can significantly reduce the size of JSON files. 253 | 254 | ### Useful Links 255 | 256 | [JSON Style Guide](https://google.github.io/styleguide/jsoncstyleguide.xml) -------------------------------------------------------------------------------- /markdown/datasets/emoticons.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Emoticons JSON Dataset" 3 | description: "Discover a delightful collection of popular emoticons at JSONLint.com. This dataset captures the essence of digital expression, providing labels, slugs, and the emoticons themselves in one encompassing JSON file." 4 | --- 5 | 6 | # Emoticons JSON Dataset 7 | 8 | This JSON file offers a collection of popular emoticons used across various digital platforms. Each emoticon entry contains the following attributes: 9 | 10 | - **Label:** The descriptive name of the emoticon. 11 | - **Slug:** A hyphen-separated version of the label for URL purposes. 12 | - **Emoticon:** The actual representation of the emoticon. 13 | 14 | Whether you're an enthusiast of digital expression or looking to implement emoticons in your applications, we hope this dataset is useful. 15 | 16 | [Download](/datasets/emoticons.json) 17 | 18 | [Open in Editor](/?url=%%NEXT_PUBLIC_BASE_URL%%/datasets/emoticons.json) 19 | 20 | **Sample Data:** 21 | 22 | ```javascript 23 | [ 24 | { 25 | "label": "Table Flip", 26 | "slug": "table-flip", 27 | "emoticon": "(╯°□°)╯︵ ┻━┻" 28 | }, 29 | { 30 | "label": "Shrug", 31 | "slug": "shrug", 32 | "emoticon": "¯\\_(ツ)_/¯" 33 | }, 34 | { 35 | "label": "Smile", 36 | "slug": "smile", 37 | "emoticon": ":-)" 38 | } 39 | ] 40 | ``` -------------------------------------------------------------------------------- /markdown/datasets/programming-languages.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Programming Languages Information JSON Dataset" 3 | description: "Dive into a detailed dataset of major programming languages at JSONLint.com. Discover foundational details like launch year, founder, primary use cases, and more in a structured JSON format." 4 | --- 5 | 6 | # Programming Languages Information JSON Dataset 7 | 8 | This JSON file offers an extensive dataset of key programming languages spanning multiple decades. For each language, the following attributes are covered: 9 | 10 | - **Name:** The official or commonly recognized name of the programming language. 11 | - **Year Launched:** The year when the language was first introduced or officially released. 12 | - **Founder:** The individual(s) or organization responsible for the creation and development of the language. 13 | - **Primary Use Cases:** The main areas or domains where the language finds its most common applications. 14 | 15 | Whether you're an educator, a software developer, a historian, or a programming enthusiast, this dataset provides a handy reference to understand the evolution and characteristics of major programming languages. 16 | 17 | [Download](/datasets/programming-languages.json) 18 | 19 | [Open in Editor](/?url=%%NEXT_PUBLIC_BASE_URL%%/datasets/programming-languages.json) 20 | 21 | **Sample Data:** 22 | 23 | ```javascript 24 | { 25 | "programming_languages": [ 26 | { 27 | "name": "Python", 28 | "year_launched": 1991, 29 | "founder": "Guido van Rossum", 30 | "primary_use_cases": "Web Development, Data Analysis, Artificial Intelligence, Scientific Computing" 31 | }, 32 | { 33 | "name": "Java", 34 | "year_launched": 1995, 35 | "founder": "James Gosling", 36 | "primary_use_cases": "Web Development, Mobile Applications, Enterprise Systems" 37 | }, 38 | { 39 | "name": "JavaScript", 40 | "year_launched": 1995, 41 | "founder": "Brendan Eich", 42 | "primary_use_cases": "Web Development, Backend Development (Node.js), Desktop Applications" 43 | }, 44 | { 45 | "name": "C++", 46 | "year_launched": 1985, 47 | "founder": "Bjarne Stroustrup", 48 | "primary_use_cases": "System Programming, Game Development, Real-Time Simulations" 49 | } 50 | ] 51 | } 52 | ``` -------------------------------------------------------------------------------- /markdown/datasets/us-states-with-detail.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "U.S. States Information JSON Dataset" 3 | description: "Explore a detailed dataset of all 50 U.S. states at JSONLint.com. From state names, capitals, to timezones and neighboring borders, get all the insights you need in one comprehensive JSON file." 4 | --- 5 | 6 | # U.S. States Information JSON Dataset 7 | 8 | This JSON file provides a comprehensive dataset of all 50 U.S. states. For each state, the following attributes are included: 9 | 10 | - **Name:** The official name of the state. 11 | - **Abbreviation:** The two-letter postal abbreviation for the state. 12 | - **Capital:** The capital city of the state. 13 | - **Incorporation Date:** The date when the state was admitted to the Union. 14 | - **Timezone:** The primary timezone in which the state is located. 15 | - **Borders:** A list of adjacent U.S. states that share a border with the state. 16 | 17 | This data can be useful for educational purposes, geographic applications, or any context where detailed information on U.S. states is needed. 18 | 19 | [Download](/datasets/us-states-with-detail.json) 20 | 21 | [Open in Editor](/?url=%%NEXT_PUBLIC_BASE_URL%%/datasets/us-states-with-detail.json) 22 | 23 | **Sample Data:** 24 | 25 | ```javascript 26 | { 27 | "states": [ 28 | { 29 | "name": "Alabama", 30 | "abbreviation": "AL", 31 | "capital": "Montgomery", 32 | "incorporation_date": "1819-12-14", 33 | "timezone": "Central Time Zone", 34 | "borders": ["Tennessee", "Georgia", "Florida", "Mississippi"] 35 | }, 36 | { 37 | "name": "Alaska", 38 | "abbreviation": "AK", 39 | "capital": "Juneau", 40 | "incorporation_date": "1959-01-03", 41 | "timezone": "Alaska Time Zone", 42 | "borders": [] 43 | }, 44 | { 45 | "name": "Arizona", 46 | "abbreviation": "AZ", 47 | "capital": "Phoenix", 48 | "incorporation_date": "1912-02-14", 49 | "timezone": "Mountain Time Zone", 50 | "borders": ["California", "Nevada", "Utah", "Colorado", "New Mexico"] 51 | } 52 | ] 53 | } 54 | ``` -------------------------------------------------------------------------------- /markdown/how-to-open-json-file.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "How to Open JSON Files" 3 | description: "Learn about JSON file compatibility, use of tools like JSON Lint for viewing, editing, and formatting JSON data, and make data interchange seamless. Ideal for beginners and experts alike." 4 | --- 5 | 6 | # How to Open JSON Files 7 | 8 | ## Creating a JSON File 9 | 10 | To harness the full potential of **JSON (JavaScript Object Notation)** files or to use JSON viewers effectively, it's essential to first understand how to create one. JSON files have a .json extension and are extremely easy to script using a compatible text editor. Here's a simple guide on crafting a JSON file from scratch. 11 | 12 | To pave the way, let's embark on the journey of creating our sample JSON file. 13 | 14 | - Open a text editor on your computer. 15 | - Create a new file with a .json extension. 16 | - Proceed by copying the sample JSON code provided below, pasting it into your newly created file. 17 | 18 | Your final product should look something like this sample JSON code: 19 | 20 | ``` 21 | { 22 | "firstName": "fname", 23 | "lastName": "lname", 24 | "gender": "male", 25 | "age": 25, 26 | "address": { 27 | "streetAddress": "26 colony", 28 | "city": "Ahemdabad", 29 | "state": "Gujarat", 30 | "postalCode": 354323 31 | }, 32 | "phoneNumbers": 33 | [ 34 | { 35 | "type": "business", 36 | "number": "9323227323" 37 | } 38 | ] 39 | } 40 | ``` 41 | 42 | Be sure to save your alterations. You've just created your first JSON file successfully! 43 | 44 | Aside from being a standard type of data interchange format, JSON has broad utility. It's often utilized to transmit data from a web application to a server, take data backups, and vice versa. To put it simply, JSON is a flexible and compact format for data storage and exchange within web applications, and its broad compatibility with various devices and platforms only adds to its appeal for developers. 45 | 46 | ## How to open a JSON file? 47 | 48 | One question that often arises is how to open a JSON file. This can be particularly confusing if you're unfamiliar with the process. Don't worry though, it's not half as daunting as it initially seems. 49 | 50 | Firstly, it's important to remember that **JSON files are compatible with a multitude of programming languages** and databases, making them versatile and widely used for data interchange between web servers and applications. They're identified by their extensions - files carrying a .json extension are, you guessed it, JSON files. 51 | 52 | One of the simplest ways to open a JSON file is by using a readymade tool, such as a [**JSON Lint**](https://jsonlint.com). JSON Lint allows you to conveniently open, view, edit, and decipher the data contained in a JSON file right on your device. 53 | 54 | Here's a quick rundown of the JSON Lint's main features: 55 | 56 | 1. **JSON Viewer:** Select and open any JSON file from your device. 57 | 2. **JSON formatter:** Effortlessly turn your JSON files into a nicely formatted and easier to read version. 58 | 59 | ## Uses of JSON Format 60 | 61 | The advanced applications of JSON files have stretched way beyond their primary purpose of transmitting data between servers and web applications. Initially, JSON files solely catered to the exchange of data between the web application and server. The format has since popularized, adapting to myriad purposes. 62 | 63 | NoSQL database engines such as **MongoDB** and **Elasticsearch**, extensively utilize the JSON structure. They leverage this format to house unstructured data in their databases. This factor adds another feather to JSON files' cap as it has become the widely accepted format in the usage spectrum of the NoSQL Database. 64 | 65 | If we nudge towards server-based JavaScript applications like node.js or reactJS, they too embody the JSON element for storing their configuration information. This mechanism allows an easy and structured pattern of data recall, bolstering the operational efficiency of the applications. 66 | 67 | Digging further into the DNA of a JSON file, it follows an elementary rule of storing data and objects in the JSON format, which is, in reality, a globally-standard format to retain and exchange data. The simplicity of a JSON file gets highlighted as users can mould it with the .json extension and it does not consume much storage space. Moreover, it's a text-based and human-readable file, meaning any compatible text editor can read and edit it. 68 | 69 | ## Benefits of Using JSON Format 70 | 71 | JSON files are versatile and easily adaptable. They're known for their compatibility with various programming languages. This format works well with JavaScript applications such as Node.js and ReactJS, alongside NoSQL database engines like MongoDB and Elasticsearch. This compatibility and usability have propelled JSON to be one of the widely-used file formats in programming. 72 | 73 | One interesting feature of JSON is its compatibility with editors across the spectrum. For instance, [**Notepad++**](https://notepad-plus-plus.org/), a source code editor, fully supports JSON along with languages like C++, Java, YAML, and HTML. Loaded with an efficient interface and plugins for added functionality, Notepad++ is a tool to reckon with when dealing with JSON. Other supported file types include TXT, AS, CMD, CS, CSS, DIZ, HTML, JSON, and so on. 74 | 75 | If we talk about accessibility, JSON files win here as well. Believe it or not, you can open your JSON files in browsers like [**Microsoft Edge**](https://www.microsoft.com/en-us/edge). The browser not only detects JSON files but also formats and syntax highlights them automatically. Microsoft Edge's JSON viewing capability sets it apart and provides a great UX for developers and non-developers alike. 76 | 77 | However, even world-class tools like this can't magically fix invalid JSON data. Examples of such invalidities include omitting double quotes around key names and trailing commas after the last key-value pair. But do not fear, your handy [JSON viewer](https://jsonlint.com) won't leave you in the dark! It does apply syntax highlighting to invalid JSON and reports the errors conveniently in the Console tool. 78 | 79 | Clearly, the benefits of JSON are hard to ignore. The simplicity, versatility, and widespread use make JSON files an asset in the digital era. No wonder they continue to impact and influence the way data is handled and transmitted in today's technologically driven world. 80 | 81 | ## Key Takeaways 82 | 83 | - JSON (JavaScript Object Notation) files are a standard type of data interchange format used for transmitting data between servers and web applications, recognized by their .json extension. 84 | - JSON files are versatile and widely utilized owing to their compatibility with various programming languages such as JavaScript, Python, PHP, and Ruby. They are editable, simple to use, and can be opened on all kinds of devices. 85 | - Creating a JSON file is a straightforward process using a compatible text editor, and involves assigning the .json extension during saving. 86 | - JSON files can be opened using tools like JSON Lint, which grant the ability to view, decipher, and even convert the JSON data into a more accessible format like PDF. 87 | - The JSON format is extensively used in NoSQL database engines like MongoDB and Elasticsearch, server-based JavaScript applications, and for storing configuration information due to its easy and structured pattern of data recall. 88 | - JSON files provide an efficient platform for data preservation and restoration. They are text-based, human-readable, consume minimal storage space, and can be easily manipulated in most text editors. 89 | 90 | ## Frequently Asked Questions 91 | 92 | ### What are the benefits of using JSON format? 93 | 94 | JSON is versatile and compatible with various programming languages. It can be easily used in JavaScript applications and NoSQL database engines. JSON files are easily stored, manipulated, and can be converted into more accessible formats. 95 | 96 | ### What applications commonly use JSON? 97 | 98 | JSON files are commonly used in JavaScript applications like Node.js and ReactJS, and in NoSQL database engines like MongoDB and Elasticsearch. 99 | 100 | ### Can JSON files be opened with regular text editors? 101 | 102 | Yes, JSON files can be opened and formatted using editors like Notepad++ and even browsers like Microsoft Edge. 103 | 104 | ### How to convert a JSON file into a more readable format? 105 | 106 | JSON files can be easily converted into more accessible formats like PDF. 107 | 108 | ### Why is JSON considered an asset in the digital era? 109 | 110 | JSON's simplicity, versatility, and widespread use influence the way data is handled and transmitted over the internet making it a crucial part of the digital era. 111 | 112 | ### How do I open a .JSON file? 113 | 114 | Assuming a Windows operating system, right-click the . json file and select Open With, then select Notepad, WordPad, or any other text editor that you have installed. If you leave the option “Always use this app to open . 115 | 116 | ### Can I open a JSON file in Excel? 117 | 118 | Go to the Data tab in an Excel Workbook. Click on From File and then choose JSON. Now, choose the JSON file from your system and select OPEN. This will open the JSON file in Excel and now you can view the data. -------------------------------------------------------------------------------- /markdown/json-parse.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "JSON.parse() in JavaScript: Your Route to Robust Data Parsing" 3 | description: "JSON.parse() in JavaScript. Learn its syntax, parameters, and dive into practical examples to master data parsing, essential for robust data handling in your projects." 4 | --- 5 | 6 | ## JSON.parse() in JavaScript 7 | 8 | `JSON.parse()` is a cornerstone method in JavaScript, pivotal for transforming JSON strings into JavaScript objects. This method is crucial for data deserialization, a necessary step for working with data received from a server or saved in a string format. 9 | 10 | ### Syntax 11 | The syntax for `JSON.parse()` is straightforward: 12 | 13 | ```javascript 14 | JSON.parse(text); 15 | JSON.parse(text, reviver); 16 | ``` 17 | 18 | - **text**: The JSON string you wish to parse. 19 | - **reviver** *(Optional)*: A function to customize the parsing process. 20 | 21 | ### Handling Different Data Types 22 | `JSON.parse()` is designed to handle JSON-formatted strings. Any deviation from the JSON format will result in a `SyntaxError`. 23 | 24 | ```javascript 25 | try { 26 | JSON.parse("undefined"); 27 | } catch (e) { 28 | console.error(e.message); // Unexpected token u in JSON at position 0 29 | } 30 | ``` 31 | 32 | ### The Reviver Parameter 33 | The reviver function is a powerful tool to filter or transform the parsed data. 34 | 35 | ```javascript 36 | let reviver = function(key, value) { 37 | if (key === "birthday") { 38 | return new Date(value); 39 | } 40 | return value; 41 | }; 42 | 43 | let jsonString = '{"name":"John", "birthday":"1990-01-01T00:00:00.000Z"}'; 44 | let obj = JSON.parse(jsonString, reviver); 45 | console.log(obj.birthday.getFullYear()); // 1990 46 | ``` 47 | 48 | ### Handling Exceptions 49 | `JSON.parse()` will throw a `SyntaxError` if the string to be parsed is not valid JSON. 50 | 51 | ```javascript 52 | try { 53 | JSON.parse("text"); 54 | } catch (e) { 55 | console.error(e.message); // Unexpected token t in JSON at position 0 56 | } 57 | ``` 58 | 59 | ### Practical Examples 60 | 61 | Various practical examples illustrating the diverse use cases of `JSON.parse()`. 62 | 63 | ```javascript 64 | // Basic Usage 65 | let jsonString = '{"name":"John", "age":30, "city":"New York"}'; 66 | let obj = JSON.parse(jsonString); 67 | console.log(obj.name); // John 68 | 69 | // Using Reviver Function 70 | let reviver = function(key, value) { 71 | if (key === "age") { 72 | return value + 1; 73 | } 74 | return value; 75 | }; 76 | 77 | let newObj = JSON.parse(jsonString, reviver); 78 | console.log(newObj.age); // 31 79 | ``` -------------------------------------------------------------------------------- /markdown/json-stringify-guide.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "JSON.stringify() in JavaScript: A Comprehensive Guide" 3 | description: "JSON.stringify() in JavaScript: its syntax, parameters, and practical examples. Master data serialization for effective data handling and transmission in your projects." 4 | --- 5 | 6 | ## JSON.stringify() in JavaScript 7 | 8 | `JSON.stringify()` is an indispensable method in JavaScript, crucial for converting JavaScript values into JSON strings. This method is pivotal for data serialization, a process essential for storing data or sending data to a server. Let's delve deeper into understanding `JSON.stringify()` through its syntax, parameters, behavior with different data types, and exceptions handling. 9 | 10 | ### Syntax 11 | 12 | The syntax for `JSON.stringify()` is as follows: 13 | 14 | ```javascript 15 | JSON.stringify(value); 16 | JSON.stringify(value, replacer); 17 | JSON.stringify(value, replacer, space); 18 | ``` 19 | 20 | - **value**: The initial JavaScript value you wish to convert. 21 | - **replacer** *(Optional)*: A function or array to customize the stringification. 22 | - **space** *(Optional)*: A parameter to beautify the output, enhancing readability. 23 | 24 | ### Handling Various Data Types 25 | 26 | `JSON.stringify()` exhibits different behaviors with various data types. Here are some scenarios: 27 | 28 | 1. **Undefined, Function, and Symbol Values**: These values are not valid JSON values and are omitted or changed to `null` during conversion. 29 | 30 | ```javascript 31 | let data = { 32 | a: undefined, 33 | b: function() {}, 34 | c: Symbol("") 35 | }; 36 | 37 | let jsonData = JSON.stringify(data); 38 | console.log(jsonData); // "{}" 39 | ``` 40 | 41 | 2. **BigInt Values**: Attempting to serialize `BigInt` values will throw a `TypeError`, unless a `toJSON()` method is defined to handle serialization. 42 | 43 | ```javascript 44 | let bigIntData = { 45 | value: BigInt(10) 46 | }; 47 | 48 | try { 49 | let jsonData = JSON.stringify(bigIntData); 50 | } catch (error) { 51 | console.error(error); // TypeError: Do not know how to serialize a BigInt 52 | } 53 | ``` 54 | 55 | ### The Replacer Parameter 56 | 57 | The replacer parameter can be a function or an array, allowing for fine-tuning of the stringification process. 58 | 59 | ```javascript 60 | let replacer = function(key, value) { 61 | if (typeof value === "string") { 62 | return undefined; 63 | } 64 | return value; 65 | } 66 | 67 | let jsonData = JSON.stringify(data, replacer); 68 | console.log(jsonData); // {"age":30} 69 | ``` 70 | 71 | ### The Space Parameter 72 | 73 | The space parameter helps in formatting the output JSON string for readability. 74 | 75 | ```javascript 76 | let jsonData = JSON.stringify(data, null, 2); 77 | console.log(jsonData); 78 | /* 79 | { 80 | "age": 30 81 | } 82 | */ 83 | ``` 84 | 85 | ### Handling Exceptions 86 | 87 | `JSON.stringify()` throws a `TypeError` if it encounters a circular reference or a `BigInt` value, unless a `toJSON()` method is defined to handle serialization. 88 | 89 | ```javascript 90 | let circularReference = {}; 91 | circularReference.myself = circularReference; 92 | 93 | try { 94 | let jsonData = JSON.stringify(circularReference); 95 | } catch (error) { 96 | console.error(error); // TypeError: Converting circular structure to JSON 97 | } 98 | ``` 99 | 100 | ### Practical Examples 101 | 102 | Let’s explore some practical examples using `JSON.stringify()` with various data sets: 103 | 104 | #### Basic Object Stringification 105 | 106 | ```javascript 107 | let person = { 108 | name: "John Doe", 109 | age: 25, 110 | city: "New York" 111 | }; 112 | let jsonString = JSON.stringify(person); 113 | console.log(jsonString); // {"name":"John Doe","age":25,"city":"New York"} 114 | ``` 115 | 116 | #### Nested Objects and Arrays 117 | 118 | ```javascript 119 | let data = { 120 | name: "John Doe", 121 | orders: [ 122 | {item: "laptop", price: 1000}, 123 | {item: "phone", price: 500} 124 | ], 125 | address: { 126 | street: "123 Main St", 127 | city: "New York" 128 | } 129 | }; 130 | let jsonString = JSON.stringify(data, null, 2); 131 | console.log(jsonString); 132 | /* 133 | { 134 | "name": "John Doe", 135 | "orders": [ 136 | { 137 | "item": "laptop", 138 | "price": 1000 139 | }, 140 | { 141 | "item": "phone", 142 | "price": 500 143 | } 144 | ], 145 | "address": { 146 | "street": "123 Main St", 147 | "city": "New York" 148 | } 149 | } 150 | */ 151 | ``` 152 | 153 | These examples provide a glimpse into how `JSON.stringify()` can be employed to serialize different data structures in JavaScript. -------------------------------------------------------------------------------- /markdown/mastering-json-format.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Mastering JSON: Benefits, Best Practices & Format Comparisons" 3 | description: "Learn why JSON stands out for web development and API integration, offering simplicity, flexibility, and language compatibility." 4 | --- 5 | 6 | # Mastering JSON Format: Advantages, Best Practices and Comparison with Other Data Formats 7 | 8 | ## What is JSON? 9 | 10 | JSON, standing for JavaScript Object Notation, is already a big player in today's era of data interchange. I'll delve into what makes JSON so standout. It's a text-based, language-independent format that allows for the easy and structured exchange of information. Boasting simplicity and being exceptionally lightweight, JSON is king when it comes to data transfer across your favorite web applications. 11 | 12 | One undeniable charm of JSON is its compatibility. It's like that friend we all need — flexible and gets along with everyone. Whether you're coding in Python, JavaScript, or C++, JSON functions seamlessly across these and many more languages. Importantly, its plain text nature makes it readable to both humans and machines. 13 | 14 | The beauty of JSON lies in its structure. Information is stored in a "key: value" pair format, which in essence is like a collection of Lego blocks. These 'blocks' or **data objects** can be assembled in various ways to form meaningful data structures. 15 | 16 | An example of a simple JSON object could be: 17 | 18 | ``` 19 | { 20 | "name": "John Doe", 21 | "age": 25, 22 | "isEmployed": true 23 | } 24 | ``` 25 | 26 | This structure makes JSON adaptable and extendable. You can add, modify, and delete key-value pairs without disrupting the system, offering unparalleled **flexibility in data storage**. 27 | 28 | In addition to supporting these object structures, JSON also supports arrays (ordered sequence of values), which further simplifies complex data representation. For instance, if you wanted to add job details for John Doe, it’d look something like this: 29 | 30 | ``` 31 | { 32 | "name": "John Doe", 33 | "age": 25, 34 | "isEmployed": true, 35 | "jobs": [ 36 | {"title": "Software Developer", "company": "TechCorp"}, 37 | {"title": "Project Manager", "company": "DeveloSoft"} 38 | ] 39 | } 40 | ``` 41 | 42 | Leveraging the power of arrays and objects, JSON can efficiently store virtually any data structure. Indeed, it is the backbone that drives today's internet, actively shaping the ways we store, retrieve, and process data. 43 | 44 | ## Advantages of Using JSON 45 | 46 | Looking into the wonderful world of JSON, it's clear there are a multitude of benefits when using this format. Let's dive deeper into why JSON makes such a significant impact in data interchange. 47 | 48 | Firstly, **simplicity and readability** play a key role in JSON's popularity. The structure is easy-to-follow, mimicking a simple key-value pair that anyone, coder or not, can grasp. It's this simplicity that helps developers quickly read, write or edit the data - a feature that doesn't go unnoticed in the fast-paced world of technology. 49 | 50 | JSON also shines in its **compatibility with various programming languages**. Languages such as JavaScript, Python, Ruby and many others natively support JSON. What does this mean? Simply put, JSON can readily integrate with these languages without any need for additional libraries. Now that's efficient. 51 | 52 | Another winning feature of JSON is its **support for arrays and objects**. This ability to handle complex data through a recognized syntax makes JSON superior in data representation to many other formats. Whether you're dealing with multi-level arrays or nested objects, JSON has you covered. 53 | 54 | One more advantage of JSON to highlight is its **lightweight nature**. JSON's format, without the need for end tags or closing tags, leads to reduced data redundancy and less data overall. This means faster data transmission and smoother execution – an essential requirement in today's digital age. 55 | 56 | In this internet era, JSON's importance in shaping how data is stored, retrieved, and processed is undeniable. From simple inventory lists to intricate game data, JSON delivers with reliability and flexibility. 57 | 58 | ## JSON vs Other Data Formats 59 | 60 | As we delve further into the nitty-gritty of JSON, it's paramount we draw comparisons between JSON and other data formats. **Two main competitors** of JSON that come to mind are XML and CSV. Understanding where JSON stands in relation to these will help define its unique value more accurately. 61 | 62 | XML, just like JSON, is human-readable and used widely for data exchange. But where JSON really shines is in its simplicity. Rather than the **verbose and complex syntax** of XML that can quickly clutter your screen, JSON stays minimal and clean, something I absolutely appreciate. JSON's format is also more condense which leads to quicker data transmissions. 63 | 64 | Well, then we have CSV. While it's true that CSV files are typically smaller, they lack the depth of JSON. In a CSV, it's challenging to represent hierarchical or multi-dimensional data. JSON, on the other hand, as we discussed earlier, has robust support for arrays and objects. It's like comparing a black-and-white photo to a 3D movie; the depth that JSON provides far outshines a mere CSV's capabilities. 65 | 66 | Let's not forget one of JSON's formidable advantages - compatibility with various programming languages. XML requires parsers to be readable in different programming languages, and CSV files often need custom parsing solutions, both of which can be cumbersome for developers. With JSON, that isn't necessary - it's supported natively in many programming languages, easing integration and reducing development time. 67 | 68 | But before we lean too far into JSON's corner, it's worth mentioning that there are scenarios where other formats may be more suitable. Binary formats like Protobuf or Avro might provide better performance for massive or complex datasets. The world of data formats isn't black and white - there are shades of grey that give room for all, each with its own use cases. 69 | 70 | Moving forward, we'll dissect how JSON is leveraged in web development, and its role in shaping APIs. By highlighting its advantages and pointing out certain usage pitfalls, this deep dive into JSON seeks to arm you with the knowledge to efficiently utilize JSON in your own projects. 71 | 72 | ## JSON Syntax 73 | 74 | Understanding the syntax is fundamental to appreciating JSON's beauty. It's this simplicity and readability that make JSON a desirable format. JSON structures data in name-value pairs, much like a JavaScript object. Yet, it's not limited to a particular set of programming languages. Its universal syntax is what allowed me to integrate it in various environments easily. 75 | 76 | The first thing to look at is **data types** that JSON supports. It can handle simple data types like strings, numbers, and Booleans – true or false. At the same time, it embraces compound types such as arrays and other JSON objects. Being adept with these data types can make the information representation more effective. 77 | 78 | Let's take a look at a JSON object: 79 | 80 | ``` 81 | { 82 | "name": "John Doe", 83 | "age": 30, 84 | "isVaccinated": true, 85 | "familyNames": ["Jane Doe", "Sam Doe"] 86 | } 87 | ``` 88 | 89 | In this JSON object, you can see different types of data. The _name_ is a string, the _age_ a number, _isVaccinated_ a Boolean, and _familyNames_ an array of strings. 90 | 91 | When it comes to arrays, they are enclosed in square brackets. Each value is separated by a comma. Here's an example of a JSON array: 92 | 93 | ``` 94 | [ 95 | {"name": "John Doe", "age": 30}, 96 | {"name": "Jane Doe", "age": 32} 97 | ] 98 | ``` 99 | 100 | This array represents a list of people, each person being a JSON object itself. 101 | 102 | Next, we'll discuss how the JSON format shapes the landscape of web development, and how it’s used in creating user-friendly and feature-rich APIs. For developers seeking to use JSON in their projects, gaining a good grasp of the format and its syntax will be time well spent. 103 | 104 | ## How to Parse JSON Data 105 | 106 | Parsing JSON data is a crucial skill in web development, making it an area that I must delve into due to its immense importance. It's necessary to understand that the process varies depending on the programming language you're using. In this regard, let's look at parsing JSON data using two popular languages, JavaScript and Python. 107 | 108 | **Parsing in JavaScript** is straightforward. JavaScript natively supports JSON through the JSON object. To parse JSON using JavaScript, developers use the JSON.parse() method, converting the JSON data into a JavaScript object. 109 | 110 | Here's a simple example: 111 | 112 | ``` 113 | var jsonData = '{"name":"John", "age":30, "city":"New York"}'; 114 | var obj = JSON.parse(jsonData); 115 | alert(obj.name); 116 | ``` 117 | 118 | In this JavaScript example, we are converting a JSON string into a JavaScript object using the JSON.parse method. The alert function then displays the name value, "John". 119 | 120 | **Parsing in Python**, on the other hand, requires the python 'json' library. Developers invoke the json.loads() method to parse JSON data. 121 | 122 | Here's a Python example: 123 | 124 | ``` 125 | import json 126 | jsonData = '{"name":"John", "age":30, "city":"New York"}'; 127 | data = json.loads(jsonData) 128 | print(data['name']) 129 | ``` 130 | 131 | In our Python example, after importing the json module, we invoke the json.loads() function to parse the JSON data into a python dictionary. The print function then outputs the name value, which is "John". 132 | 133 | Take note that converting JSON data into another data structure (for instance, a Python dictionary or JavaScript object) is called **deserialization**. It's an essential part of using JSON format in web development, allowing you to process the data as per your needs. As you work with JSON, remember to keep the syntax rules in mind to ensure data integrity. The ease with which JSON integrates into your coding process is what makes it a front runner in data interchange formats. 134 | 135 | ## JSON Schema Validation 136 | 137 | Moving onward, let's delve into a crucial element associated with JSON - that's right, we're talking about JSON schema validation. This integral feature of JSON ensures code standardization, guarantees the integrity of data, and promotes a smooth coding process. 138 | 139 | So what is JSON schema validation? Essentially, it's a powerful tool that validates your JSON data and checks if it adheres to the predefined specifications. And yes, it does all of this _before_ you import that data into your JavaScript or Python environments, saving you from potential headaches. 140 | 141 | Here's how it works. When you're transferring data between applications using JSON, the data structure should be predictable and standardized. JSON schema validation, as its name suggests, is like a blueprint or a model for your data. It outlines what your data should look like - what elements it should contain, what data types those elements should be, whether certain fields are required or optional, and even the acceptable range of values for certain elements. 142 | 143 | **Applying JSON schema validation can significantly improve your overall coding experience.** It enables you to catch and address inconsistencies and errors early on, reducing debugging efforts. It helps maintain consistent data structures across multiple applications, which really comes in handy for large-scale projects involving various teams. 144 | 145 | Take a look at this simple example of JSON schema: 146 | 147 | ``` 148 | { 149 | "type": "object", 150 | "properties": { 151 | "firstName": { 152 | "type": "string" 153 | }, 154 | "age": { 155 | "type": "integer", 156 | "minimum": 0 157 | } 158 | }, 159 | "required": ["firstName", "age"] 160 | } 161 | ``` 162 | 163 | In this example, the schema defines an object that needs to have two properties, `firstName` and `age`. `firstName` should be a string, whereas `age` should be an integer and cannot be a negative value. 164 | 165 | Now that we've understood the concept of JSON schema validation, we'll be moving onto another exciting topic- creating custom JSON schemas. This will require another deep dive and you'll need your concentration caps on for this one. So, let's proceed... 166 | 167 | ## Best Practices for Using JSON 168 | 169 | JSON format is intuitive and offers a lot of flexibility, but to get the most out of it, it's crucial to follow certain best practices. These practices streamline the coding process, aid readability and optimize data interchange. 170 | 171 | First, always keep the JSON structure clean and organized. JSON data is represented in name-value pairs, meaning proper structuring ensures data integrity. It's easy to fall prey to messy code when dealing with complex data, so I emphasize consistency and neatness. 172 | 173 | Secondly, utilize JSON schema validation to its fullest extent. As explained before, JSON schema validation ensures code standardization and aids in catching inconsistencies early. A well-implemented validation process helps maintain the robustness of data interchange. 174 | 175 | In addition, when dealing with large strings of data, it's better to use arrays rather than multiple name-value pairs. Data arrays in JSON are simple to understand and can hold data more efficiently than multiple name-value pairs. 176 | 177 | When creating custom JSON schemas for complex data, remember to keep things as simple as possible. Simplicity is the key to meaningful data representation in JSON. 178 | 179 | Below, I've compiled a basic guide to JSON best practices: 180 | 181 | - **Maintain clean, organized structure:** Do this by using consistent name-value pairs and avoid nesting data unnecessarily. 182 | - **Use JSON schema validation:** Early detection of inconsistencies avoids future problems. 183 | - **Use arrays for large strings of data:** Arrays are easier to manage and are intuitive for other developers. 184 | - **Keep schemas simple:** Don't overcomplicate data representation. 185 | 186 | These practices don't just apply to JSON -- they're a solid foundation for any data interchange format. The true power of these principles shines through when they're used consistently throughout a project. Get into this habit, and you'll see a marked improvement in your coding efficiency. While working with JSON, you'll soon discover other practices that can boost your experience - shaping and tailoring these guidelines to your workflow is equally important. 187 | 188 | In the next section, we'll delve into comparing JSON with other data interchange formats - looking at where JSON stands out and where it might not be the best option. That's for another discussion though, so let's place the bookmark here. 189 | 190 | ## Conclusion 191 | 192 | So we've seen how JSON's simplicity and readability make it a powerful tool for data interchange. Its schema validation feature is a game changer, ensuring code standardization and catching errors early. I've shared some best practices for using JSON, like maintaining a clean structure, using arrays for large data strings, and keeping schemas simple. Remember, these aren't exclusive to JSON and can be applied to other data interchange formats too. In the next section, we'll dive into how JSON stacks up against other data formats. Stay tuned! -------------------------------------------------------------------------------- /markdown/mastering-json-in-javascript.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Mastering JSON in JavaScript: Comprehensive Examples and Techniques" 3 | description: "Just like any other programming or scripting language, JSON has specific data types too. While these are simple and easy to understand, it's essential to get a good grasp of these since JSON data types form the backbone of effective JSON syntax manipulation." 4 | --- 5 | 6 | # Mastering JSON in JavaScript: Comprehensive Examples and Techniques 7 | 8 | ## What is JSON? 9 | 10 | Stepping into the core topic of our discussion, let's unravel the concept of **JSON**. JSON, or JavaScript Object Notation, is a lightweight data-interchange format that is easy to read and write for humans, and easy for machines to parse and generate. 11 | 12 | JSON's primary purpose is data transmission between a server and a web application, serving as an alternative to XML. The backbone of JSON's effectiveness lies in its format; it's text-based, language independent, and designed comprised of two structures: 13 | 14 | - A collection of name/value pairs. 15 | - An ordered list of values. 16 | 17 | Consider the former as an object, map, or hash table and the latter akin to an array, list, or sequence. 18 | 19 | You might be wondering, what does JSON look like? To give a clear picture, let's take a basic example. 20 | 21 | ``` 22 | { 23 | "name": "John Doe", 24 | "age": 30, 25 | "isAlive": true, 26 | "hobbies": ["reading", "traveling", "swimming"] 27 | } 28 | ``` 29 | 30 | This snippet shows a JSON representation of a person's essential details. It's quite similar to a dictionary in Python or an object in JavaScript, isn't it? The main highlight is not just its simplicity but its universal nature, allowing it to be used across various languages. 31 | 32 | At first glance, JSON might appear intimidating, especially with all the curly brackets, commas, and quotes. But as we dig deeper and start getting our hands dirty, we'll find that it's a robust and handy tool, living up to its reputation. 33 | 34 | ## JSON Syntax 35 | 36 | Plunging into the realm of **JSON**, one cannot overlook the significance of understanding its syntax. A stronghold in the JSON structure, syntax is the fundamental framework that molds data into the JSON standard. So let's break it down. 37 | 38 | First and foremost, data in JSON is represented in name/value pairs. Imagine these as the keys and values that you'd see in a general dictionary or map. They're enshrined in curly braces `{}` thereby forming an object. For example: 39 | 40 | ``` 41 | { 42 | "Color": "Blue", 43 | "Shape": "Square" 44 | } 45 | ``` 46 | 47 | In the instance above, `"Color"` and `"Shape"` are the names/keys, whereas `"Blue"` and `"Square"` are the respective values. Notice that both the names and the string values are enclosed within double quotes `" "`. 48 | 49 | Next, we tackle JSON's arrays. Akin to JavaScript arrays, JSON arrays are an ordered list of values tucked within square brackets `[]`. Every value within this list can be of any type: a string, a number, another object, or even another array. Here's how it's depicted: 50 | 51 | ``` 52 | { 53 | "Colors": ["Blue", "Red", "Green"] 54 | } 55 | ``` 56 | 57 | In this scenario, `"Colors"` is an array housing three values. 58 | 59 | I must stress that JSON syntax is case-sensitive. `"color"` and `"Color"` are considered distinct. Pay heed to the capitalization! 60 | 61 | For representing numeric, null, or Boolean values, we forego the quotes: 62 | 63 | ``` 64 | { 65 | "Age": 45, 66 | "Is_Married": true, 67 | "Children": null 68 | } 69 | ``` 70 | 71 | Here, `45`, `true`, and `null` are not padded with quotes marking their numeric, Boolean, and null nature respectively. 72 | 73 | In essence, JSON syntax revolves around these foundational rules. It's elegant and straightforward once grounded in these principles. Keep practicing, and you'll find yourself an adept JSON navigator in no time. 74 | 75 | ## JSON Data Types 76 | 77 | Just like any other programming or scripting language, JSON has specific data types too. While these are simple and easy to understand, **it's essential to get a good grasp of these since JSON data types form the backbone of effective JSON syntax manipulation**. So, let's dive into the most common ones. 78 | 79 | First off, **String**. String in JSON is a sequence of characters enclosed in double quotes. Here's an example: `"firstName": "John"`. Notice how both the key and value are enclosed in quotes. 80 | 81 | Next up, **Number**. This is a numeric value, and it doesn't need to be in quotes. For example, `"age": 30` represents a numeric value. 82 | 83 | Thirdly, we have the aptly-named **Boolean**. This includes either of the two literal values: `true` or `false`. An example of this would be `"isMarried": true`. 84 | 85 | The **Array** is a bit different. It's an ordered collection of values, represented inside square brackets. Here's how you use it: `"children": ["Ann", "Ben"]`. 86 | 87 | Along the same lines, there's **Object**. This one's a collection of key/value pairs, represented inside curly braces. For instance, `{ "name":"John", "age":30, "city":"New York" }`. 88 | 89 | Finally, there's **Null**, which is a type with one single possible value: `null`. It's used to signify the absence of any value. 90 | 91 | In the following Markdown table, I've summarized the different JSON data types that we've just discussed: 92 | 93 | 94 | | Data Type | Example | 95 | |-----------|---------------------------------------------------| 96 | | String | `"firstName": "John"` | 97 | | Number | `"age": 30` | 98 | | Boolean | `"isMarried": true` | 99 | | Array | `"children": ["Ann", "Ben"]` | 100 | | Object | `{ "name":"John", "age":30, "city":"New York" }` | 101 | | Null | `"middleName": null` | 102 | 103 | Remember, becoming proficient in JSON isn't about memorizing these data types but knowing how to use them effectively. Keep practicing, and you'll get the hang of it in no time. 104 | 105 | ## JSON Objects 106 | 107 | Moving forward in our offerings on JSON, let's delve into JSON objects. 108 | 109 | JSON objects are key-value pairs grouped together using curly braces {}. Object keys are treated as strings, enclosed in double quotes, while values can take any data type - whether it be numbers, strings, booleans, arrays, other JSON objects, or null values. It's an incredibly versatile tool for data organization. 110 | 111 | Here's a simple JSON object example: 112 | 113 | ``` 114 | { 115 | "firstName": "John", 116 | "lastName": "Doe", 117 | "age": 30 118 | } 119 | ``` 120 | 121 | In this snippet, "firstName", "lastName", and "age" are the keys while "John", "Doe", and 30 are their corresponding values. 122 | 123 | Remember, while JSON might initially seem complicated, **practice is key**. Start with simple JSON objects, understanding their keys and values, and gradually move to more complicated scenarios. 124 | 125 | Now consider a slightly more complex JSON object: 126 | 127 | ``` 128 | { 129 | "student": { 130 | "name": "Emily", 131 | "age": 21, 132 | "subjects": ["Math", "Science"] 133 | } 134 | } 135 | ``` 136 | 137 | In this example, "student" is the key and its value is another JSON object - creating what's termed a nested JSON object. From the nested object, "name", "age", and "subjects" are keys while "Emily", 21, and \["Math", "Science"\] are the corresponding values. Notice how arrays can also be used as values in JSON objects. 138 | 139 | JSON objects follow a certain syntax - keys must be strings, each key-value pair is separated by a colon, different key-value pairs are separated by a comma and finally, the entire object is enclosed in curly braces. Practice with different kinds of data and combinations to better understand JSON objects. Notice how little details like missing colons or misplaced commas can lead to errors - ensuring such details are correct is an essential part of mastering JSON. 140 | 141 | So, keep experimenting, and you'll discover the true depth of what JSON objects can do. 142 | 143 | Notably, real-world applications of JSON are endless, from transferring data between the client and server in web applications, to Facebook's Graph API, to modernizing legacy systems - the list goes on and on. As you gain proficiency, you'll begin to unlock the power of JSON and its related technologies. 144 | 145 | Above was a brief into JSON objects. In the next section, we'll throw light on Arrays in JSON. 146 | 147 | ## JSON Arrays 148 | 149 | After grasping the concept of JSON objects, it's time to explore another crucial component of JSON - arrays. 150 | 151 | Just like an object, a JSON array is also enclosed within brackets \[\]. However, what sets an array apart from an object is the type of data it holds. Arrays store and manage sequences of values, rather than key-value pairs. The arrangement carries significant relevance since arrays preserve the order, which can be beneficial for many applications. 152 | 153 | Let me show you a **simple JSON array** to start things off. It's an array of books, each represented by its title: 154 | 155 | ``` 156 | [ 157 | "Pride and Prejudice", 158 | "To Kill a Mockingbird", 159 | "1984" 160 | ] 161 | ``` 162 | 163 | An array is not merely confined to holding simple datatype values; it **can contain other arrays, objects, or even a combination** of the two! 164 | 165 | Consider the below **nested JSON array** where an array is holding other book-related arrays: 166 | 167 | ``` 168 | [ 169 | ["Pride and Prejudice", "Jane Austen"], 170 | ["To Kill a Mockingbird", "Harper Lee"], 171 | ["1984", "George Orwell"] 172 | ] 173 | ``` 174 | 175 | Notice how the above array groups each title and author? This allows us to handle related sets of data within one structured package. 176 | 177 | As if that's not exciting enough, JSON arrays can also hold arrays **of JSON objects**. Observe this booklist array containing book objects: 178 | 179 | ``` 180 | [ 181 | {"title": "Pride and Prejudice", "author": "Jane Austen"}, 182 | {"title": "To Kill a Mockingbird", "author": "Harper Lee"}, 183 | {"title": "1984", "author": "George Orwell"} 184 | ] 185 | ``` 186 | 187 | Carving out structured data like the above is a breeze with JSON. It frees us up to create more intricate data patterns that perfectly align with our requirements. 188 | 189 | Learning JSON arrays, like understanding objects, comes mostly through practice. Be ready to dive into every range, create scenarios, and work out solutions. The greater the challenges you undertake, the better you'll get. That's the beauty of working with such a dynamic, flexible tool as JSON. 190 | 191 | ## Working with JSON in JavaScript 192 | 193 | Now that we've got a grasp of JSON arrays, let's dive into **how to work with JSON in JavaScript**. It's crucial to note, JSON is a native JavaScript object. That means JavaScript understands JSON and can easily translate its data. 194 | 195 | So, how do we do that? 196 | 197 | #### Parse JSON in JavaScript 198 | 199 | JavaScript offers a global object JSON with built-in methods for parsing - `JSON.parse()`. When I receive data from a server, the data is always a string. If the data is JSON, I can parse it into a JavaScript object with `JSON.parse()`. The `JSON.parse()` method takes a JSON string and transforms it into a JavaScript object. I've often found this method valuable when working on AJAX calls. 200 | 201 | ``` 202 | let jsonData = '{"name":"John", "age":30, "city":"New York"}'; 203 | let obj = JSON.parse(jsonData); 204 | console.log(obj.name); // John 205 | ``` 206 | 207 | In this example, `jsonData` is a JSON document. Utilizing `JSON.parse()`, `jsonData` is converted into a JavaScript object. 208 | 209 | #### Stringify JSON in JavaScript 210 | 211 | There's also the `JSON.stringify()` method. This method takes a JavaScript object and turns it into a JSON string. It's useful when I need to send a JavaScript object to a server. 212 | 213 | ``` 214 | let obj = {name: "John", age: 30, city: "New York"}; 215 | let myJSON = JSON.stringify(obj); 216 | console.log(myJSON); // {"name":"John", "age":30, "city":"New York"} 217 | ``` 218 | 219 | In the example above, `obj` is a JavaScript object, which is transformed into a JSON string through the `JSON.stringify()` method. 220 | 221 | That said, always remember JSON and JavaScript have a **harmonious relationship**. It's a relationship that enables easy manipulation and interaction of data in web applications. I encourage you to practice these examples, experiment, and explore the potential that JSON offers in JavaScript programming. 222 | 223 | ## Conclusion 224 | 225 | I've walked you through the essentials of JSON in JavaScript, highlighting the ease of translation between the two. We've seen the power of built-in methods like JSON.parse() and JSON.stringify() in action. These methods are your gateway to converting JSON strings into JavaScript objects and vice versa. Now it's your turn. I encourage you to dive in, practice these methods, and unlock the potential of JSON in your JavaScript programming. Remember, mastering JSON can significantly streamline your coding process and open up new possibilities in data handling. Happy coding! -------------------------------------------------------------------------------- /markdown/privacy.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "JSONLint Privacy Policy" 3 | description: "At JSONLint.com, one of our main priorities is the privacy of our visitors. This Privacy Policy document contains types of information that is collected and recorded by JSONLint.com and how we use it." 4 | --- 5 | 6 | ## JSONLint.com Privacy Policy 7 | 8 | At JSONLint.com, one of our main priorities is the privacy of our visitors. This Privacy Policy document contains types of information that is collected and recorded by JSONLint.com and how we use it. 9 | 10 | If you have additional questions or require more information about our Privacy Policy, do not hesitate to contact us via our [Github](https://github.com/circlecell/jsonlint.com) page. 11 | 12 | Log Files 13 | 14 | JSONLint.com follows a standard procedure of using log files. These files log visitors when they visit websites. All hosting companies do this and a part of hosting services' analytics. The information collected by log files include internet protocol (IP) addresses, browser type, Internet Service Provider (ISP), date and time stamp, referring/exit pages, and possibly the number of clicks. These are not linked to any information that is personally identifiable. The purpose of the information is for analyzing trends, administering the site, tracking users' movement on the website, and gathering demographic information. 15 | 16 | Cookies and Web Beacons 17 | 18 | Like any other website, JSONLint.com uses 'cookies'. These cookies are used to store information including visitors' preferences, and the pages on the website that the visitor accessed or visited. The information is used to optimize the users' experience by customizing our web page content based on visitors' browser type and/or other information. 19 | 20 | DoubleClick DART Cookie 21 | 22 | Google is one of a third-party vendor on our site. It also uses cookies, known as DART cookies, to serve ads to our site visitors based upon their visit to JSONLint.com and other sites on the internet. However, visitors may choose to decline the use of DART cookies by visiting the Google ad and content network Privacy Policy at the following URL – [http://www.google.com/privacy\_ads.html](https://www.google.com/privacy_ads.html). 23 | 24 | Our Advertising Partners 25 | 26 | Some of advertisers on our site may use cookies and web beacons. Our advertising partners include: 27 | 28 | * Google 29 | * BuySellAds 30 | 31 | Each of our advertising partners has their own Privacy Policy for their website. For easier access, an updated and hyperlinked resource is maintained here: 32 | 33 | Privacy Policies 34 | 35 | You may consult this list to find the Privacy Policy for each of the advertising partners of JSONLint.com. 36 | 37 | Third-party ad servers or ad networks uses technologies like cookies, JavaScript, or Web Beacons that are used in their respective advertisements and links that appear on JSONLint.com, which are sent directly to users' browser. They automatically receive your IP address when this occurs. These technologies are used to measure the effectiveness of their advertising campaigns and/or to personalize the advertising content that you see on websites that you visit. 38 | 39 | Note that JSONLint.com has no access to or control over these cookies that are used by third-party advertisers. 40 | 41 | Third Part Privacy Policies 42 | 43 | JSONLint.com's Privacy Policy does not apply to other advertisers or websites. Thus, we are advising you to consult the respective Privacy Policies of these third-party ad servers for more detailed information. It may include their practices and instructions about how to opt-out of certain options. You may find a complete list of these Privacy Policies and their links here: Privacy Policy Links. 44 | 45 | You can choose to disable cookies through your individual browser options. To know more detailed information about cookie management with specific web browsers, it can be found at the browsers' respective websites. What Are Cookies? 46 | 47 | Children's Information 48 | 49 | Another part of our priority is adding protection for children while using the internet. We encourage parents and guardians to observe, participate in, and/or monitor and guide their online activity. 50 | 51 | JSONLint.com does not knowingly collect any Personal Identifiable Information from children under the age of 13. If you think that your child provided this kind of information on our website, we strongly encourage you to contact us immediately and we will do our best efforts to promptly remove such information from our records. 52 | 53 | Online Privacy Policy Only 54 | 55 | This privacy policy applies only to our online activities and is valid for visitors to our website with regards to the information that they shared and/or collect in JSONLint.com. This policy is not applicable to any information collected offline or via channels other than this website. 56 | 57 | Consent 58 | 59 | By using our website, you hereby consent to our Privacy Policy and agree to its terms and conditions. -------------------------------------------------------------------------------- /next.config.js: -------------------------------------------------------------------------------- 1 | const result = require('dotenv').config() 2 | 3 | module.exports = { 4 | reactStrictMode: false, 5 | async redirects() { 6 | return [ 7 | { 8 | source: '/icons/icon-hires.png', 9 | destination: '/images/logo.png', 10 | permanent: true, 11 | } 12 | ] 13 | } 14 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jsonlint.com", 3 | "private": true, 4 | "scripts": { 5 | "dev": "next dev", 6 | "build": "next build", 7 | "start": "next start", 8 | "lint": "next lint" 9 | }, 10 | "dependencies": { 11 | "@tailwindcss/aspect-ratio": "^0.4.2", 12 | "@tailwindcss/typography": "^0.5.9", 13 | "@uiw/react-codemirror": "^4.21.18", 14 | "codemirror": "^5.65.15", 15 | "copy-to-clipboard": "^3.3.3", 16 | "dotenv": "^16.3.1", 17 | "gray-matter": "^4.0.3", 18 | "jsonlint-mod": "^1.7.6", 19 | "nanoid": "^4.0.2", 20 | "next": "^13.4.7", 21 | "next-navigation": "^1.0.6", 22 | "react": "^18.2.0", 23 | "react-codemirror2": "^7.2.1", 24 | "react-dom": "^18.2.0", 25 | "remark": "^15.0.1", 26 | "remark-html": "^16.0.1", 27 | "tailwind-merge": "^1.14.0", 28 | "tailwindcss-animate": "^1.0.6", 29 | "xml2js": "^0.6.2" 30 | }, 31 | "devDependencies": { 32 | "autoprefixer": "^10.4.2", 33 | "eslint": "^8.7.0", 34 | "eslint-config-next": "^12.0.4", 35 | "postcss": "^8.4.5", 36 | "tailwindcss": "^3.0.15" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /pages/[...slug]/index.js: -------------------------------------------------------------------------------- 1 | import fs from 'fs' 2 | import path from 'path' 3 | import matter from 'gray-matter' 4 | import { remark } from 'remark' 5 | import html from 'remark-html' 6 | 7 | const markdownDirectory = path.join(process.cwd(), 'markdown') 8 | 9 | function getAllMarkdownFiles(dir, fileList = []) { 10 | const files = fs.readdirSync(dir) 11 | 12 | files.forEach(file => { 13 | if (fs.statSync(path.join(dir, file)).isDirectory()) { 14 | fileList = getAllMarkdownFiles(path.join(dir, file), fileList) 15 | } else if (file.endsWith('.md')) { 16 | const filePath = path.join(dir, file) 17 | fileList.push(filePath) 18 | } 19 | }) 20 | 21 | return fileList 22 | } 23 | 24 | export async function getStaticPaths() { 25 | const markdownFiles = getAllMarkdownFiles(markdownDirectory) 26 | const slugs = markdownFiles.map(file => { 27 | const relativePath = path.relative(markdownDirectory, file) 28 | return relativePath.replace('.md', '').split(path.sep) 29 | }) 30 | 31 | return { 32 | paths: slugs.map(slug => ({ params: { slug: slug } })), 33 | fallback: false 34 | } 35 | } 36 | 37 | export async function getStaticProps({ params }) { 38 | 39 | const slugPath = params.slug.join('/') 40 | const fullPath = path.join(markdownDirectory, `${slugPath}.md`) 41 | 42 | if (!fs.existsSync(fullPath)) { 43 | return { notFound: true } 44 | } 45 | 46 | const fileContents = fs.readFileSync(fullPath, 'utf8') 47 | const { data, content } = matter(fileContents) 48 | const contentWithEnv = content.replace(/%%NEXT_PUBLIC_BASE_URL%%/g, process.env.NEXT_PUBLIC_BASE_URL) 49 | const processedContent = await remark().use(html).process(contentWithEnv) 50 | const contentHtml = processedContent.toString() 51 | 52 | const metaTags = [] 53 | if (data.description) { 54 | metaTags.push({ 55 | attribute: 'name', 56 | value: 'description', 57 | content: data.description 58 | }) 59 | } 60 | 61 | const datasetsDirectory = path.join(markdownDirectory, 'datasets') 62 | const datasetFiles = getAllMarkdownFiles(datasetsDirectory) 63 | 64 | const allDatasets = datasetFiles.map(filePath => { 65 | const relativePath = path.relative(datasetsDirectory, filePath) 66 | const slug = relativePath.replace('.md', '').replace(path.sep, '/') 67 | const displayName = slug.split('/').pop().split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ') 68 | return { slug, displayName } 69 | }) 70 | 71 | return { 72 | props: { 73 | slug: slugPath, 74 | content: contentHtml, 75 | title: data.title, 76 | metaTags: metaTags, 77 | allDatasets: allDatasets.filter(dataset => dataset.slug !== params.slug.join('/')) 78 | } 79 | } 80 | } 81 | 82 | export default function Page({ slug, title, content, allDatasets }) { 83 | 84 | const isDatasetPage = slug.startsWith('datasets/') 85 | 86 | return ( 87 |
88 |
89 |
90 | 91 | {isDatasetPage && ( 92 |
93 |

Additional JSON Datasets

94 |
95 | {allDatasets.map(dataset => ( 96 | 97 | {dataset.displayName} 98 | 99 | ))} 100 |
101 |
102 | )} 103 | 104 |
105 |
106 | ) 107 | } -------------------------------------------------------------------------------- /pages/_app.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect, useRef } from 'react' 2 | import Layout from '../components/Layout' 3 | import { useRouter } from 'next/router' 4 | import Head from 'next/head' 5 | import ValidContext from '../contexts/ValidContext' 6 | import useExtensionCheck from '../hooks/useExtensionCheck' 7 | import Script from 'next/script' 8 | 9 | import '@/styles/globals.css' 10 | 11 | export default function App({ Component, pageProps }) { 12 | 13 | const [isValid, setIsValid] = useState(null) 14 | const router = useRouter() 15 | 16 | const isExtensionInstalled = useExtensionCheck() 17 | 18 | const [checksComplete, setChecksComplete] = useState(false) 19 | 20 | useEffect(() => { 21 | if (isExtensionInstalled !== null) { 22 | setChecksComplete(true); 23 | } 24 | }, [isExtensionInstalled]) 25 | 26 | useEffect(() => { 27 | if (checksComplete) { 28 | window.fullres ||= {events:[]} 29 | 30 | window.fullres.metadata = { 31 | isChromeExtensionInstalled: isExtensionInstalled 32 | } 33 | 34 | const handleRouteChange = () => { 35 | const script = document.getElementById('fullres') 36 | if (script) return 37 | 38 | const newScript = document.createElement('script') 39 | newScript.async = true 40 | newScript.src = 'https://jsonlint.com/omwRUQbcAI/jsonlint.js?' + (new Date() - new Date() % 43200000) 41 | newScript.id = 'fullres' 42 | newScript.attributes.siteKeyOverride = 'jsonlint' 43 | document.head.appendChild(newScript) 44 | } 45 | 46 | handleRouteChange() 47 | router.events.on('routeChangeComplete', handleRouteChange) 48 | 49 | return () => { 50 | router.events.off('routeChangeComplete', handleRouteChange) 51 | } 52 | } 53 | }, [checksComplete, isExtensionInstalled, router.events]) 54 | 55 | return ( 56 | <> 57 | 58 | {pageProps.title} 59 | {pageProps.metaTags && 60 | pageProps.metaTags.map((tag, index) => ( 61 | 62 | )) 63 | } 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 |
76 | 77 | 78 | 79 | 80 | 81 |
82 |