Created
March 21, 2020 22:02
-
-
Save tomhodgins/a708b97a6a36ee9f453e8a37a4348195 to your computer and use it in GitHub Desktop.
Storing every type JSON supports in CSSOM using CSS custom properties, and in DOM using data attributes. Then JavaScript can access the string values of these properties and attributes, and JSON.parse() can return the result not as a string but as the actual JS object it represents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<style> | |
json- { | |
--string: "Hello World"; | |
--number: 1e3; | |
--object: {"hello": "world"}; | |
--array: [1, 2, 3]; | |
--true: true; | |
--false: false; | |
--null: null; | |
} | |
</style> | |
<json- | |
data-string='"Hello World"' | |
data-number='1e3' | |
data-object='{"hello": "world"}' | |
data-array='[1, 2, 3]' | |
data-true='true' | |
data-false='false' | |
data-null='null' | |
></json-> | |
<script> | |
const values = { | |
js: { | |
string: 'Hello World', | |
number: 1e3, | |
object: {hello: 'world'}, | |
array: [1, 2, 3], | |
true: true, | |
false: false, | |
null: null | |
}, | |
dom: {}, | |
cssom: {} | |
} | |
const properties = [ | |
'string', | |
'number', | |
'object', | |
'array', | |
'true', | |
'false', | |
'null' | |
] | |
// Add parsed values from DOM | |
properties.forEach(property => | |
values.dom[property] = JSON.parse( | |
document.querySelector('json-').dataset[property] | |
) | |
) | |
// Add parsed values from CSSOM | |
properties.forEach(property => | |
values.cssom[property] = JSON.parse( | |
getComputedStyle(document.querySelector('json-')).getPropertyValue(`--${property}`) | |
) | |
) | |
// Parsed values | |
console.dir(values) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment