About This Article
This article was created using an automated generation workflow leveraging generative AI. Based on the specifications of Microsoft Learn for ConvertTo-Json and ConvertFrom-Json, we have organized reproduction steps and decision methods using fictitious equipment data.Verification Status: 📘 Referencing official specifications – Operations not performed on a physical PowerShell machine
Does Nesting Disappear with PowerShell's ConvertTo-Json? Observing Structure by Changing Depth
When generating JSON in PowerShell, department names and contacts may be displayed on the screen, but when the saved JSON is passed to another system, intermediate information may turn into strings. Especially when assembling configuration files or data sent to APIs, it is dangerous to judge normality based on appearance alone. One candidate cause is the ConvertTo-Json of -Depth. This time, without calling external services, we will observe the relationship between hierarchies and conversion results using fictitious data in memory.
- First, What Happens
- Safe Experiment: Converting the Same Data Twice
- Visual Overview: The Boundary Between Data and JSON Conversion
- Going a Step Further: Reconverting from JSON to Verify the Structure
- Changing Just One Condition: What Improves When You Increase the Depth?
- Troubleshooting Upon Failure
- Decision-Making in Business Applications
- Summary
- Official Documentation and Primary Sources
First, What Happens
For example, consider a scenario where the General Affairs Department creates JSON for equipment management and hands it over to another person in charge. Suppose you want to combine not only the equipment name, but also the management department and the contact information of that department into a single piece of data. In PowerShell, you can naturally represent this by nesting hashtables. However, the depth limit when converting to JSON is specified separately from the depth of the data structure on PowerShell. It is also a separate issue whether the converted JSON is syntactically correct and whether the necessary attributes remain.
What we want to check here is whether changing Depth simply increases the character count, or whether the object structure itself changes. Please make a prediction and then compare the two results. The code to run is short, assuming PowerShell 7, and does not require administrator privileges or network connection.
Safe Experiment: Converting the Same Data Twice
Open PowerShell 7 and execute the following as a single block. Do not include real business contacts or API tokens; use only fictitious names and phone numbers. The code does not create files, it just outputs strings to the screen.
$item = @{
item = '架空ノートPC'
owner = @{
department = '総務'
contact = @{
name = '担当A'
extension = '0000'
}
}
}
'=== depth 2 ==='
$item | ConvertTo-Json -Depth 2
'=== depth 5 ==='
$item | ConvertTo-Json -Depth 5
What to pay attention to is whether owner inside contact remains as a JSON object. The default depth is 2. In places where depth is insufficient, the original object may not be expressed as the expected nested JSON and may be converted to a string. PowerShell 7.1 and later also have a specification that issues a warning when the specified depth is exceeded. Observe not only the presence or absence of warnings, but also the quotation marks and braces of the conversion results.
-Depth 5On the side where it is set to contact, this relatively small nesting is assumed to be expressed as a JSON object. However, what is posted is the expected behavior derived from the specification, and is not an actual measurement log obtained by running PowerShell on Windows at the time of creating this article. Once executed, line up both outputs and check whether there is a brace immediately after
Visual Overview: The Boundary Between Data and JSON Conversion
The following diagram illustrates where the depth specification takes effect when converting a PowerShell nested structure into JSON. Even with the same data on the left, the output structure changes if the conversion conditions differ. The branches in the diagram are conceptual illustrations to aid understanding and do not imply the exact function call order of the internal PowerShell implementation.
flowchart TD
A["入れ子のPowerShellオブジェクト"] --> B["ConvertTo-Json"]
B --> C{"Depthは十分か"}
C -->|はい| D["入れ子をJSONオブジェクトとして表現"]
C -->|いいえ| E["深い部分が期待どおりの構造にならない"]
D --> F["受け手がキーをたどれる"]
E --> G["構造を確認しDepthを見直す"]
The key takeaway from this diagram is that even if JSON syntax validation succeeds, it does not necessarily mean the recipient on the right can traverse the expected keys. For example,owner.contact.namein processing that assumes the hierarchy ofcontactifnameis serialized as a string, the nested key under it cannot be retrieved. This is why you should inspect the JSON before transmission rather than suspecting a downstream receiver failure.
Going a Step Further: Reconverting from JSON to Verify the Structure
Simply looking at strings on a screen can cause you to miss quotation marks or escape characters. Converting the output back into a PowerShell object and verifying whether the target value is a plain string or an object with attributes makes it easier to evaluate. The following example reloads the JSON generated with sufficient depth and retrieves the contact person's name.
$json = $item | ConvertTo-Json -Depth 5 $restored = $json | ConvertFrom-Json $restored.owner.contact.name $restored.owner.contact.GetType().FullName
The expected contact person's name is担当A. Because type name displays depend on the execution environment and the object representation after conversion, fixed string matches should not be used as the sole pass criterion. The important thing is thatcontactis restored not merely as a string, but as a structure capable of referencingname. If$restored.owner.contact.namehappens to be empty, do not immediately assume the entire JSON was empty. First, investigate whether that position in the original JSON was an object or a string.
ConvertFrom-Jsonis a process for reading JSON contents, not a general-purpose serializer intended to fully restore the types and fine-grained properties of the original PowerShell object. Here, it is used as a tool to check whether the key hierarchy expected by the JSON receiver is maintained. Treat this separately from tests aimed at complete parity with the original types.
Changing Just One Condition: What Improves When You Increase the Depth?
Only-Depth 2in the initial code is changed to-Depth 5. The input data, PowerShell version, and destination remain unchanged. This makes it easier to conclude that any differences in the output are caused by the depth setting. Do not make a longer output the sole success criterion; instead, verify whether the three-tier hierarchy ofowner、contact、namecan be traversed as JSON keys.
On the other hand, unconditionally specifying a very large number does not guarantee safety. Increasing the depth may result in unintended internal data being included in the output. For API payloads, explicitly constructing a new hashtable with only the required keys is sometimes safer than converting the entire input object as-is. Count the required nesting levels and configure values that match your expected schema.
What this comparison reveals is thatDepthis not a setting that determines "how many lines to display on the screen," but rather a setting that determines how deeply nesting is handled during conversion. Even if the PowerShell values before conversion are correct, the shape of the information can change at the stage of determining the output format. When troubleshooting data integration issues, it is helpful to examine the conversion conditions between input and output.
Troubleshooting Upon Failure
The first thing to check is whether PowerShell itself is throwing an error, or whether the JSON was successfully generated but is not in the expected structure. In the former case, record the error message and version. In the latter case, extract the relevant part of the JSON and check the quotation marks and braces. Because the causes are not necessarily the same in both cases, it is important not to mix troubleshooting steps.
Next, verify the actual specified-Depthvalue and the PowerShell version. If you were relying on default values, change to explicit specification and compare the differences. Regarding warnings in PowerShell 7.1 and later, do not treat the absence of visible warnings as "proof that the depth was sufficient." Because it depends on how warnings are handled and how the host displays them, directly inspecting the output structure is more reliable.
If it still does not behave as expected, check whether the source data contains keys with the same name, whether$nullare mixed in, or whether arrays and single objects are being confused. BlamingDepthfor issues that are not resolved by changing the depth will cause you to overlook other problems. It is safest to start by keeping only the minimum target data and confirming whether it can be reproduced with unnecessary attributes removed.
Furthermore, simply verifying that the JSON syntax is valid is not enough. Ensure that the required keys, value types, and formats—such as whether something is an array or an object—match what the recipient expects. JSON is not just a string; it is a format for passing data structures. The practical acceptance criterion is not only whether the values can be read, but whether the recipient can reach those values via the expected path.
Decision-Making in Business Applications
For example, when sending JSON to an API such as Microsoft Graph, check the shape of the locally generated request body before chasing errors at the destination. However, because required keys and types differ for each API, this does not mean the sample provided here can be used as-is with an API. Prioritize designing a dedicated data structure tailored to the API specifications and converting only the necessary hierarchy.
The same applies when outputting configuration files. First, output using dummy data, read the JSON back in to confirm that the required hierarchy remains, and then apply it to the actual data. It is also important not to output data containing sensitive information directly to the screen or logs. Ensure that displaying JSON for troubleshooting does not inadvertently lead to the leakage of credentials or personal information.
If you are automating the process, check for the presence of required keys after conversion before proceeding. The key point is not to treat the mere generation of JSON as a successful completion, but rather to inspect the required structure. If the expected keys are missing, abort transmission or overwriting, and review the sample hierarchy and conversion conditions. There is no need to perform actual file replacement or API POST requests using this learning code.
Lastly, remember to divide the location of the problem into three areas: Is the source data in PowerShell correct? Was the shape preserved during JSON conversion? Does it match the recipient's specifications? Investigating these in order allows you to move beyond ad-hoc responses of simply increasing-Depthand progress toward reproducible data integration testing.
Summary
ConvertTo-JsonThe-Depthparameter is not merely an option for formatting the appearance of JSON; it is a crucial setting for preserving nested structures. By changing the depth by one using the same dummy data and reading the output JSON back in withConvertFrom-Json, you can verify whether the recipient can reach the expected keys. Inspecting the depth specification, output structure, and destination schema separately is the shortcut to reducing practical errors.
Official Documentation and Primary Sources
Microsoft Learn — ConvertTo-Json:https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json
Microsoft Learn — ConvertFrom-Json:https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertfrom-json
