Build a new JSON shape from parsed fields.

reshape-data Programs often parse one shape, compute a few values, and stringify a smaller shape for the next step.

Reshaping Data

tax
reshape_data.js
Replay: real traced execution (multi-file project)
const tax = 2;
const text = "{\"subtotal\":20,\"customer\":\"Lee\"}";
const customer = JSON.parse(text).customer;
const total = JSON.parse(text).subtotal + tax;
const summary = JSON.stringify({ customer: customer, total: total });

console.log("tax=" + tax);
console.log("summary=" + summary);
const tax = 0;
const text = "{\"subtotal\":20,\"customer\":\"Lee\"}";
const customer = JSON.parse(text).customer;
const total = JSON.parse(text).subtotal + tax;
const summary = JSON.stringify({ customer: customer, total: total });

console.log("tax=" + tax);
console.log("summary=" + summary);
const tax = 5;
const text = "{\"subtotal\":20,\"customer\":\"Lee\"}";
const customer = JSON.parse(text).customer;
const total = JSON.parse(text).subtotal + tax;
const summary = JSON.stringify({ customer: customer, total: total });

console.log("tax=" + tax);
console.log("summary=" + summary);
  1. tax ← 2, text ← {"subtotal":20,"customer":"Lee"}, customer ← Lee

    1const tax→ 2 = 2; //@tax=0, 52const text→ {"subtotal":20,"customer":"Lee"} = "{\"subtotal\":20,\"customer\":\"Lee\"}";3const customer→ Lee = JSON.parse(text{"subtotal":20,"customer":"Lee"}).customer;4const total→ 22 = JSON.parse(text→ {"subtotal":20,"customer":"Lee"}).subtotal + tax2;5const summary→ {"customer":"Lee","total":22} = JSON.stringify({ customer: customerLee, total: total22 });67console.log("tax=" + tax2);8console.log("summary=" + summary{"customer":"Lee","total":22});
    outputtax=2
    summary={"customer":"Lee","total":22}
  1. tax ← 0, text ← {"subtotal":20,"customer":"Lee"}, customer ← Lee

    1const tax→ 0 = 0;2const text→ {"subtotal":20,"customer":"Lee"} = "{\"subtotal\":20,\"customer\":\"Lee\"}";3const customer→ Lee = JSON.parse(text{"subtotal":20,"customer":"Lee"}).customer;4const total→ 20 = JSON.parse(text→ {"subtotal":20,"customer":"Lee"}).subtotal + tax0;5const summary→ {"customer":"Lee","total":20} = JSON.stringify({ customer: customerLee, total: total20 });67console.log("tax=" + tax0);8console.log("summary=" + summary{"customer":"Lee","total":20});
    outputtax=0
    summary={"customer":"Lee","total":20}
  1. tax ← 5, text ← {"subtotal":20,"customer":"Lee"}, customer ← Lee

    1const tax→ 5 = 5;2const text→ {"subtotal":20,"customer":"Lee"} = "{\"subtotal\":20,\"customer\":\"Lee\"}";3const customer→ Lee = JSON.parse(text{"subtotal":20,"customer":"Lee"}).customer;4const total→ 25 = JSON.parse(text→ {"subtotal":20,"customer":"Lee"}).subtotal + tax5;5const summary→ {"customer":"Lee","total":25} = JSON.stringify({ customer: customerLee, total: total25 });67console.log("tax=" + tax5);8console.log("summary=" + summary{"customer":"Lee","total":25});
    outputtax=5
    summary={"customer":"Lee","total":25}