### JSONCrush Usage Example (HTML)
Source: https://github.com/killedbyapixel/jsoncrush/blob/master/README.md
Demonstrates how to use JSONCrush within an HTML file, including importing the module and performing compression and decompression. This example highlights the practical application of JSONCrush for web development.
```html
JSONCrush Demo
```
--------------------------------
### JavaScript: Compress and Uncompress JSON Strings with JSONCrush
Source: https://github.com/killedbyapixel/jsoncrush/blob/master/index.html
This snippet demonstrates the core functionality of JSONCrush. It shows how to import the library, crush a given string into a compact format, and then uncrush it back to its original form. It also includes a basic check to verify if the original and uncrushed strings match, updating the UI accordingly. This is useful for reducing the size of JSON data for transmission or storage.
```javascript
"use strict";
// First import JSONCrush as a module.
import JSONCrush from './JSONCrush.js';
textarea_JSON.oninput =()=> {
// Get your string to crush.
const stringToCrush = textarea_JSON.value;
// Just call JSON crush to crush your string!
const crushed = JSONCrush.crush(stringToCrush);
// To uncrush call JSONUncrush on the crushed string.
const uncrushed = JSONCrush.uncrush(crushed);
// We can verify that the uncrushed string matches the orginal string
div_crush_result.innerHTML = stringToCrush == uncrushed ? "SUCCESS: Strings match!" : "ERROR: Strings don't match!";
textarea_crushed_uri.value = crushed;
textarea_uncrushed.value = uncrushed;
}
```
--------------------------------
### JavaScript: Run Unit Tests for JSONCrush Compression
Source: https://github.com/killedbyapixel/jsoncrush/blob/master/index.html
This code snippet provides a function to execute a series of predefined unit tests for the JSONCrush library. It iterates through an array of test strings, crushes and uncrushes each one, and compares the results. The function reports the success or failure of each test, including the percentage of size difference after compression and any errors encountered. This is essential for ensuring the reliability and accuracy of the JSONCrush compression algorithm.
```javascript
button_unitTests.onclick =()=> {
// Some tests that can be run to ensure that JSONCrush is working correctly...
let output = 'Unit Test Results...';
for(const testString of unitTests) {
let crushed = '', uncrushed = '', error = '';
try {
crushed = JSONCrush.crush(testString);
uncrushed = JSONCrush.uncrush(crushed);
} catch (e) {
error = e.message;
}
const length1 = encodeURIComponent(testString).length;
const length2 = encodeURIComponent(crushed).length;
const percent = 100 * length2 / length1;
output += '' + testString + '
';
if (testString != uncrushed) {
output += 'FAIL! ';
if (error)
output += 'Error: ' + error;
else
output += "Crushed string doesn't match: '" + uncrushed + "'";
} else
output += 'PASS! Size Difference: ' + percent.toFixed(2) + '%';
if (length2 > length1)
output += ' Compressed is larger!';
output += '
';
}
div_unit_test_results.innerHTML = output;
}
const unitTests = [
'This is the first unit test, feel free to add more.',
'{"students":[{"name":"Jack","age":17},{"name":"Jill","age":16},{"name":"Sue","age":16}],"class":"math"}',
'{"shaderStatements":[{"output":"b","outputSwizzle":"zxyw","assignmentOperator":"-=","functionName":"","parameter":"a","valueX":6.62,"valueY":6.165,"valueZ":-0.974,"valueW":-4.233,"parameterSwizzle":"xzyy"},{"output":"b","outputSwizzle":"ywxz","assignmentOperator":"-=","functionName":"","parameter":"a","valueX":-4.88,"valueY":0.649,"valueZ":0.171,"valueW":-0.084,"parameterSwizzle":"yzwx"},{"output":"a","outputSwizzle":"xzwy","assignmentOperator":"*=","functionName":"logA","parameter":"b","valueX":-2.368,"valueY":-7.284,"valueZ":-5.01,"valueW":-0.005,"parameterSwizzle":"zzwz"},{"output":"b","outputSwizzle":"xwzy","assignmentOperator":"-=","functionName":"sin","parameter":"b","valueX":-3.686,"valueY":-3.258,"valueZ":-4.059,"valueW":-8.506,"parameterSwizzle":"wwzz"},{"output":"b","outputSwizzle":"zxyw","assignmentOperator":"=","functionName":"ceil","parameter":"b","valueX":5.36,"valueY":-8.274,"valueZ":0.002,"valueW":5.429,"parameterSwizzle":"xxwy"},{"output":"a","outputSwizzle":"xzwy","assignmentOperator":"=","functionName":"","parameter":"b","valueX":-3.353,"valueY":-5.681,"valueZ":-7.792,"valueW":1.254,"parameterSwizzle":"zyxw"},{"output":"b","outputSwizzle":"ywxz","assignmentOperator":"+=","functionName":"floor","parameter":"a","valueX":6.669,"valueY":-0.05,"valueZ":-8.629,"valueW":-2.802,"parameterSwizzle":"xyyw"},{"output":"b","outputSwizzle":"xywz","assignmentOperator":"+=","functionName":"fract","parameter":"a","valueX":0.103,"valueY":-3.118,"valueZ":0.255,"valueW":6.287,"parameterSwizzle":"xyyw"},{"output":"a","outputSwizzle":"zxyw","assignmentOperator":"/=","functionName":"ceil","parameter":"","valueX":5.484,"valueY":-1.26,"valueZ":8.705,"valueW":-1.59,"parameterSwizzle":"zyyw"},{"output":"a","outputSwizzle":"wyzx","assignmentOperator":"=","functionName":"sqrtA","parameter":"b","valueX":-0.366,"valueY":-0.117,"valueZ":0.162,"valueW":1.761,"parameterSwizzle":"yywy"},{"output":"a","outputSwizzle":"yxzw","assignmentOperator":"*=","functionName":"atan","parameter":"b","valueX":3.743,"valueY":-0.003,"valueZ":4.636,"valueW":0.056,"parameterSwizzle":"wxxw"},{"output":"b","outputSwizzle":"zwxy","assignmentOperator":"=","functionName":"","parameter":"","valueX":6.083,"valueY":-6.322,"valueZ":0.032,"valueW":0.428,"parameterSwizzle":"yzyy"},{"output":"a","outputSwizzle":"zxyw","assignmentOperator":"/=","functionName":"","parameter":"a","valueX":0.151,"valueY":1.024,"valueZ":-2.862,"valueW":3.193,"parameterSwizzle":"xzyx"},{"output":"a","outputSwizzle":"zwxy","assignmentOperator":"*=","functionName":"","parameter":"a","valueX":-1.637,"valueY":1.828,"valueZ":1.924}]}
```
--------------------------------
### Compress JSON Data in Node.js
Source: https://context7.com/killedbyapixel/jsoncrush/llms.txt
This snippet shows how to use JSONCrush in a Node.js environment to compress JSON objects. It includes a comparison between original and crushed string sizes and demonstrates how to tune the compression performance using the maxSubstringLength parameter.
```javascript
import JSONCrush from 'jsoncrush';
const apiResponse = { users: [{ id: 1, name: 'Alice' }], pagination: { page: 1 } };
const jsonString = JSON.stringify(apiResponse);
const crushed = JSONCrush.crush(jsonString);
console.log(`Original: ${jsonString.length} chars`);
console.log(`Crushed: ${crushed.length} chars`);
const largeJson = JSON.stringify({ data: Array(1000).fill({ key: 'value' }) });
const crushedFast = JSONCrush.crush(largeJson, 30);
const crushedBetter = JSONCrush.crush(largeJson, 100);
```
--------------------------------
### Manage Application State in URLs with JSONCrush
Source: https://context7.com/killedbyapixel/jsoncrush/llms.txt
This snippet demonstrates how to serialize, compress, and encode application state into a URL parameter, and how to reverse the process to restore state upon page load. It uses the browser's History API to update the URL without triggering a page refresh.
```javascript
import JSONCrush from './JSONCrush.js';
function saveStateToUrl(state) {
const jsonString = JSON.stringify(state);
const crushed = JSONCrush.crush(jsonString);
const encoded = encodeURIComponent(crushed);
const newUrl = `${window.location.pathname}?state=${encoded}`;
window.history.pushState(state, '', newUrl);
return newUrl;
}
function loadStateFromUrl() {
const params = new URLSearchParams(window.location.search);
const encoded = params.get('state');
if (!encoded) return null;
try {
const crushed = decodeURIComponent(encoded);
const jsonString = JSONCrush.uncrush(crushed);
return JSON.parse(jsonString);
} catch (e) {
console.error('Failed to load state:', e);
return null;
}
}
```
--------------------------------
### Compress JSON with JSONCrush.crush
Source: https://context7.com/killedbyapixel/jsoncrush/llms.txt
Demonstrates how to compress a JSON string into a URL-safe format. The resulting string can be further encoded for use in web URLs to reduce payload size.
```javascript
import JSONCrush from './JSONCrush.js';
const jsonData = '{"students":[{"name":"Jack","age":17},{"name":"Jill","age":16},{"name":"Sue","age":16}],"class":"math"}';
const crushed = JSONCrush.crush(jsonData);
const shareableUrl = `https://example.com/app?data=${encodeURIComponent(crushed)}`;
console.log(shareableUrl);
```
--------------------------------
### Decompress JSON with JSONCrush.uncrush
Source: https://context7.com/killedbyapixel/jsoncrush/llms.txt
Shows how to reverse the compression process to recover the original JSON string. This is essential for retrieving data passed through URL parameters.
```javascript
import JSONCrush from './JSONCrush.js';
const crushed = "('students!~(name!'Jack'~age!17_name!'Jill'~age!16_name!'Sue'~age!16)~~class!'math')_";
const original = JSONCrush.uncrush(crushed);
const data = JSON.parse(original);
console.log(data.students[0].name);
```
--------------------------------
### Compress JSON String with JSONCrush (JavaScript)
Source: https://github.com/killedbyapixel/jsoncrush/blob/master/README.md
Compresses a JSON string into a URL-friendly format using the JSCrush algorithm. This function is optimized for URI-encoded JSON strings and can significantly reduce their size. The algorithm uses a special delimiter '\u0001' which is removed if present in the input.
```javascript
import JSONCrush from './JSONCrush.js';
const jsonString = '{"students":[{"name":"Jack","age":17},{"name":"Jill","age":16},{"name":"Sue","age":16}],"class":"math"}';
const crushedString = JSONCrush.crush(jsonString);
console.log(crushedString); // Example output: ('students!%5B*Jack-7.Jill-6.Sue-6)%5D~class!'math')*('name!'-'~age!1.)%2C*%01.-*_
const encodedString = encodeURIComponent(crushedString);
console.log(encodedString); // Example output: ('students!%255B*Jack-7.Jill-6.Sue-6)%255D~class!'math')*('name!'-'~age!1.)%252C*%01.-*_
const uncrushedString = JSONCrush.uncrush(crushedString);
console.log(uncrushedString);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.