Parse Nested JSON

by jacobwsmith

JavaScript

console.clear()

const parseNestedJson = (json) => {
  const parsedJson = (json[0] === '{' || json[0] === '[') ? JSON.parse(json) : json;
  if(Array.isArray(parsedJson)){
  	return parsedJson.reduce((acc, current, index) => {
      acc[index] = parseNestedJson(current);
      return acc;
    }, []);
  }
  if(typeof parsedJson === 'object') {	
    return Object.entries(parsedJson).reduce((acc, [key, value], index) => {
      acc[key] = parseNestedJson(value);
      return acc;
    }, {});
  }
 /*  if(typeof parsedJson === 'string' && ()){
  
  } */
  return parsedJson;
}


// TESTS
{
	// Test nested objects
	const input = "{\"entryFees\":[{\"fee\":\"10\",\"display\":\"$10\"},{\"fee\":\"20\",\"display\":\"$20\"},{\"fee\":\"50\",\"display\":\"$50\"},{\"fee\":\"100\",\"display\":\"$100\"},{\"fee\":\"250\",\"display\":\"$250\"},{\"fee\":\"500\",\"display\":\"$500\"},{\"fee\":\"750\",\"display\":\"$750\"},{\"fee\":\"1000\",\"display\":\"$1000\"}],\"statesOperate\": \"CA,FL,AK,GA,ME,MN,MD,MI,NC,ND,OK,NM,RI,SC,SD,UT,TX,WV,WI,WY,DC\",\"contests\":[{\"title\":\"SURVIVE THE BIRDIES\",\"description\":\"Pick 5 different golfers each daily round. Earn 1 point for each birdie or better. Each round, the top 50% of entries ranked on leaderboard (from most points to least) survive; bottom 50% are eliminated. Last remaining Survivor(s) win (or split) the cash prize.\",\"schedule\":[{\"display\":\"Thu Oct-31 - World Golf Championships-HSBC Champions\",\"value\":\"2019-10-31 07:00:00\"},{\"display\":\"Thu Nov-14 - Mayakoba Golf Classic\",\"value\":\"2019-11-14 07:00:00\"}],\"message\":\"You are invited to Survive! The basics of the contest are below. Full rules are detailed in the app. MAY THE BEST SURVIVOR WIN! \",\"fantasyPointStructureID\":1,\"leagueID\":1,\"prizePercentage\": \"0.83\",\"contestNumber\": \"1\",\"playersInvited\": \"100\",\"league\":\"PGA\"}]}"
  const inputString = input; //JSON.stringify(input);
  const result = parseNestedJson(inputString);
 ...