Deep Type Summary
JavaScript
Medium
2 views
Problem Description
You get one JSON value (can be nested). Traverse all nested values and count how many times each type appears: number, string, boolean, null, array, object. Print counts as JSON object.
Input Format
One line JSON value.
Output Format
One line JSON object.
Sample Test Case
Input:
{"a":[1,2,null],"b":{"x":true}}
Output:
{"number":2,"string":0,"boolean":1,"null":1,"array":1,"object":2}
Constraints
Total nodes up to 2e5.
Official Solution
const fs=require('fs');const s=fs.readFileSync(0,'utf8').trim();if(!s)process.exit(0);const root=JSON.parse(s);const cnt={number:0,string:0,boolean:0,null:0,array:0,object:0};const st=[root];while(st.length){const v=st.pop();if(v===null){cnt.null++;continue;}if(Array.isArray(v)){cnt.array++;for(let i=v.length-1;i>=0;i--)st.push(v[i]);continue;}const t=typeof v;if(t==='number')cnt.number++;else if(t==='string')cnt.string++;else if(t==='boolean')cnt.boolean++;else if(t==='object'){cnt.object++;for(const k of Object.keys(v))st.push(v[k]);}}process.stdout.write(JSON.stringify(cnt));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!