POWERSHELL / CHAPTER 09
JSON and CSV as data contracts
IntermediatePreserve meaning when objects cross a text boundary.
By the end of this chapter
- Choose serialization depth deliberately
- Keep identifiers distinct from numeric quantities
- Convert imported text according to a validated schema
The idea
Serialization turns object data into a format another process or future run can read. JSON distinguishes strings, numbers, arrays, and objects, but it does not preserve every PowerShell or .NET runtime type and method. Choose ConvertTo-Json depth for the actual nesting, then test the decoded structure. A visually plausible JSON string is not enough if nested values were reduced to an unintended representation.
CSV is a tabular text format whose imported field values generally need explicit conversion before numeric computation. Preserve identifiers such as 007 as strings when leading zeroes matter; convert a count only after validating its format and range. Define required fields, optional fields, and null behavior at the boundary. Round-trip tests should check meaningful values and shapes, not whitespace or property display formatting.
$json = '{"id":"007","count":2}'
$record = $json | ConvertFrom-Json
"$($record.id):$($record.count + 1)"007:3
JSON keeps id as text and count as a number, so the identifier keeps its leading zeroes while arithmetic increments the count.
Try it yourself
Serialize a nested report with an explicit depth, decode it, and check both a nested numeric value and a leading-zero identifier.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING