Canonical JSON Hash
JavaScript
Hard
6 views
Problem Description
Given a JSON object, create canonical JSON by sorting keys recursively, then compute 32-bit FNV-1a hash of that canonical string. Print hash as unsigned integer.
Input Format
One line JSON object.
Output Format
One integer hash.
Constraints
Total keys up to 2e5.
Official Solution
const fs=require('fs');const s=fs.readFileSync(0,'utf8').trim();if(!s)process.exit(0);const obj=JSON.parse(s);const norm=v=>{if(v===null)return null;if(Array.isArray(v))return v.map(norm);if(typeof v==='object'){const out={};const keys=Object.keys(v).sort();for(const k of keys)out[k]=norm(v[k]);return out;}return v;};const canon=JSON.stringify(norm(obj));let h=2166136261>>>0;for(let i=0;i<canon.length;i++){h^=canon.charCodeAt(i);h=Math.imul(h,16777619)>>>0;}process.stdout.write(String(h>>>0));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!