Skip to content

Fix JSON Editor to display existing data in visual mode on mount#4977

Open
pzyyll wants to merge 2 commits into
QuantumNous:mainfrom
pzyyll:fix/json-editor-visual-init-display
Open

Fix JSON Editor to display existing data in visual mode on mount#4977
pzyyll wants to merge 2 commits into
QuantumNous:mainfrom
pzyyll:fix/json-editor-visual-init-display

Conversation

@pzyyll
Copy link
Copy Markdown

@pzyyll pzyyll commented May 19, 2026

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

修复渠道参数覆盖新增参数后,返回设置页面后未正常显示新增加的参数BUG。

📝 变更描述 / Description

(简述:做了什么?为什么这样改能生效?请基于你对代码逻辑的理解来写,避免粘贴未经整理的内容)

之前:JsonEditor 的 rows 状态初始化为空数组,而 value 和 jsonValue 状态则初始化为 prop value。value !== jsonValue 这个 useEffect 保护条件在挂载时总是为 false,导致 parseJsonToRows 不会执行。
修复:rows 通过一个懒初始化的 useState initializer 同步初始化,使用共享的 parseJsonRows

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

  • Closes # (如有)

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 IssuesPRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

(请在此粘贴截图、关键日志或测试报告,以证明变更生效)

  • 新增参数:
屏幕截图 2026-05-19 203554
  • 修复前,未正常显示:
屏幕截图 2026-05-19 203606
  • 修复后,正确显示:
image

Summary by CodeRabbit

Release Notes

  • Refactor
    • Improved JSON editor's parsing and initialization logic for enhanced handling of invalid JSON input and better overall reliability during editing operations.

Review Change Stack

pzyyll and others added 2 commits May 2, 2026 14:53
…ount

Previously, the JsonEditor rows state was initialized as an empty array,
while the value and jsonValue states were initialized to the prop value. The
useEffect guard `value !== jsonValue` would always be false on mount,
preventing parseJsonToRows from ever running. This caused visual mode to
display empty state even when the value prop contained valid JSON.

Now, rows is initialized synchronously via a lazy useState initializer
using a shared parseJsonRows helper, which also replaces the inline parse
logic. Invalid JSON values still gracefully fall through to empty rows
(null return preserved on parse failure).
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 19, 2026

Walkthrough

A JsonEditor component's JSON parsing logic is refactored: a new parseJsonRows(json) helper standardizes conversion from JSON text to editor rows, and the component's state initialization is updated to use this helper during setup, replacing the prior empty-rows pattern.

Changes

JSON Editor Parsing Refactor

Layer / File(s) Summary
parseJsonRows helper and state initialization
web/default/src/components/json-editor.tsx
New parseJsonRows(json) helper returns EditorRow[] or null, handling empty input ([]), valid JSON objects (mapped rows), and invalid JSON (null). Component state initialization is updated to derive initial rows from parseJsonRows(value) ?? [] and initialize jsonValue state from value, replacing prior setup with empty rows and deferred parsing.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

A parser, once hidden and deep,
Now stands proud where helpers keep,
Rows spring forth from JSON's embrace,
Clean initialization takes place—
The refactor hops on! 🐰

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main fix: JsonEditor now properly displays existing JSON data in visual mode on component mount, which directly addresses the bug described in the PR objectives.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@web/default/src/components/json-editor.tsx`:
- Around line 46-61: parseJsonRows currently calls Object.entries(parsed)
without ensuring parsed is a plain object; update parseJsonRows to validate
after JSON.parse that parsed is an object suitable for key/value rows (i.e.,
typeof parsed === 'object', parsed !== null, and !Array.isArray(parsed)) and
return null for any non-object JSON (arrays, primitives, strings). Keep the
existing mapping to EditorRow and id generation when the check passes; ensure
the validation occurs before calling Object.entries so non-object inputs yield
null.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 13eace38-c115-48c8-bce3-d22ed893ea32

📥 Commits

Reviewing files that changed from the base of the PR and between 2d1ca15 and 317c7e3.

📒 Files selected for processing (1)
  • web/default/src/components/json-editor.tsx

Comment on lines +46 to +61
function parseJsonRows(json: string): EditorRow[] | null {
try {
if (!json.trim()) {
return []
}

const parsed = JSON.parse(json)
return Object.entries(parsed).map(([key, val], index) => ({
id: `${Date.now()}-${index}`,
key,
value: typeof val === 'object' ? JSON.stringify(val) : String(val),
}))
} catch (_error) {
return null
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add type validation to ensure parsed JSON is a plain object.

The function calls Object.entries(parsed) without checking whether parsed is actually an object. Non-object JSON values will produce incorrect results:

  • Arrays like [1, 2, 3] become rows with numeric string keys ("0", "1", "2")
  • Primitives like 123 or true become empty rows (data loss)
  • Strings like "hello" become character-indexed rows

Since the component is designed for key-value pairs (objects only), add a type guard after parsing to return null for non-object types.

🛡️ Proposed fix to validate object type
 function parseJsonRows(json: string): EditorRow[] | null {
   try {
     if (!json.trim()) {
       return []
     }
 
     const parsed = JSON.parse(json)
+    if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
+      return null
+    }
+    
     return Object.entries(parsed).map(([key, val], index) => ({
       id: `${Date.now()}-${index}`,
       key,
       value: typeof val === 'object' ? JSON.stringify(val) : String(val),
     }))
   } catch (_error) {
     return null
   }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function parseJsonRows(json: string): EditorRow[] | null {
try {
if (!json.trim()) {
return []
}
const parsed = JSON.parse(json)
return Object.entries(parsed).map(([key, val], index) => ({
id: `${Date.now()}-${index}`,
key,
value: typeof val === 'object' ? JSON.stringify(val) : String(val),
}))
} catch (_error) {
return null
}
}
function parseJsonRows(json: string): EditorRow[] | null {
try {
if (!json.trim()) {
return []
}
const parsed = JSON.parse(json)
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
return null
}
return Object.entries(parsed).map(([key, val], index) => ({
id: `${Date.now()}-${index}`,
key,
value: typeof val === 'object' ? JSON.stringify(val) : String(val),
}))
} catch (_error) {
return null
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/default/src/components/json-editor.tsx` around lines 46 - 61,
parseJsonRows currently calls Object.entries(parsed) without ensuring parsed is
a plain object; update parseJsonRows to validate after JSON.parse that parsed is
an object suitable for key/value rows (i.e., typeof parsed === 'object', parsed
!== null, and !Array.isArray(parsed)) and return null for any non-object JSON
(arrays, primitives, strings). Keep the existing mapping to EditorRow and id
generation when the check passes; ensure the validation occurs before calling
Object.entries so non-object inputs yield null.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant