MCPcopy Create free account
hub / github.com/cloudflare/agents / setJsonPathValue

Function setJsonPathValue

packages/shell/src/extras.ts:250–299  ·  view source on GitHub ↗
(
  root: unknown,
  tokens: PathToken[],
  value: unknown
)

Source from the content-addressed store, hash-verified

248}
249
250function setJsonPathValue(
251 root: unknown,
252 tokens: PathToken[],
253 value: unknown
254): void {
255 if (tokens.length === 0) {
256 throw new Error("JSON update path must not be empty");
257 }
258 let current = root as Record<string, unknown> | unknown[];
259 for (let index = 0; index < tokens.length - 1; index++) {
260 const token = tokens[index];
261 const nextToken = tokens[index + 1];
262 if (typeof token === "number") {
263 if (!Array.isArray(current)) {
264 throw new Error(`JSON update expected array at [${token}]`);
265 }
266 if (current[token] === undefined) {
267 current[token] = typeof nextToken === "number" ? [] : {};
268 }
269 current = current[token] as Record<string, unknown> | unknown[];
270 } else {
271 if (
272 current === null ||
273 typeof current !== "object" ||
274 Array.isArray(current)
275 ) {
276 throw new Error(`JSON update expected object at "${token}"`);
277 }
278 if ((current as Record<string, unknown>)[token] === undefined) {
279 (current as Record<string, unknown>)[token] =
280 typeof nextToken === "number" ? [] : {};
281 }
282 current = (current as Record<string, unknown>)[token] as
283 | Record<string, unknown>
284 | unknown[];
285 }
286 }
287 const finalToken = tokens[tokens.length - 1];
288 if (typeof finalToken === "number") {
289 if (!Array.isArray(current)) {
290 throw new Error(`JSON update expected array at [${finalToken}]`);
291 }
292 current[finalToken] = value;
293 } else {
294 if (current === null || typeof current !== "object") {
295 throw new Error(`JSON update expected object at "${finalToken}"`);
296 }
297 (current as Record<string, unknown>)[finalToken] = value;
298 }
299}
300
301function deleteJsonPathValue(root: unknown, tokens: PathToken[]): void {
302 if (tokens.length === 0) {

Callers 1

updateJsonValueFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected