MCPcopy Create free account
hub / github.com/Noumena-Network/code / addItemToJSONCArray

Function addItemToJSONCArray

src/utils/json.ts:258–307  ·  view source on GitHub ↗
(content: string, newItem: unknown)

Source from the content-addressed store, hash-verified

256}
257
258export function addItemToJSONCArray(content: string, newItem: unknown): string {
259 try {
260 // If the content is empty or whitespace, create a new JSON file
261 if (!content || content.trim() === '') {
262 return jsonStringify([newItem], null, 4)
263 }
264
265 // Strip BOM before parsing - PowerShell 5.x adds BOM to UTF-8 files
266 const cleanContent = stripBOM(content)
267
268 // Parse the content to check if it's valid JSON
269 const parsedContent = parseJsonc(cleanContent)
270
271 // If the parsed content is a valid array, modify it
272 if (Array.isArray(parsedContent)) {
273 // Get the length of the array
274 const arrayLength = parsedContent.length
275
276 // Determine if we are dealing with an empty array
277 const isEmpty = arrayLength === 0
278
279 // If it's an empty array we want to add at index 0, otherwise append to the end
280 const insertPath = isEmpty ? [0] : [arrayLength]
281
282 // Generate edits - we're using isArrayInsertion to add a new item without overwriting existing ones
283 const edits = modify(cleanContent, insertPath, newItem, {
284 formattingOptions: { insertSpaces: true, tabSize: 4 },
285 isArrayInsertion: true,
286 })
287
288 // If edits could not be generated, fall back to manual JSON string manipulation
289 if (!edits || edits.length === 0) {
290 const copy = [...parsedContent, newItem]
291 return jsonStringify(copy, null, 4)
292 }
293
294 // Apply the edits to preserve comments (use cleanContent without BOM)
295 return applyEdits(cleanContent, edits)
296 }
297 // If it's not an array at all, create a new array with the item
298 else {
299 // If the content exists but is not an array, we'll replace it completely
300 return jsonStringify([newItem], null, 4)
301 }
302 } catch (e) {
303 // If parsing fails for any reason, log the error and fallback to creating a new JSON array
304 logError(e)
305 return jsonStringify([newItem], null, 4)
306 }
307}

Callers 1

Calls 3

stripBOMFunction · 0.90
jsonStringifyFunction · 0.85
logErrorFunction · 0.70

Tested by

no test coverage detected