{"record":{"id":"8383cc09007f1676","repo":"jackwener/OpenCLI","slug":"label-returned-invalid-json-8383cc","errorCode":null,"errorMessage":"${label} returned invalid JSON","messagePattern":"(.+?) returned invalid JSON","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"clis/instagram/comment.js","lineNumber":32,"sourceCode":"        },\n        { name: 'text', required: true, positional: true, help: 'Comment text' },\n        { name: 'index', type: 'int', default: 1, help: 'Post index (1 = most recent)' },\n    ],\n    columns: ['status', 'user', 'text'],\n    pipeline: [\n        { navigate: 'https://www.instagram.com' },\n        { evaluate: `(async () => {\n  const username = \\${{ args.username | json }};\n  const commentText = \\${{ args.text | json }};\n  const idx = \\${{ args.index }} - 1;\n  if (!Number.isInteger(idx) || idx < 0) throw new Error('index must be a positive integer');\n  const headers = { 'X-IG-App-ID': '936619743392459' };\n  const opts = { credentials: 'include', headers };\n  async function readInstagramJson(response, label) {\n    try {\n      return await response.json();\n    } catch {\n      throw new Error(label + ' returned invalid JSON');\n    }\n  }\n  function getPostFromFeed(feed, label) {\n    if (!feed || typeof feed !== 'object' || !Array.isArray(feed.items)) {\n      throw new Error(label + ' returned malformed items payload');\n    }\n    if (idx >= feed.items.length) throw new Error('Post index ' + (idx + 1) + ' not found');\n    const post = feed.items[idx];\n    const pkRaw = post?.pk ?? post?.id;\n    const pk = typeof pkRaw === 'number' ? String(pkRaw) : (typeof pkRaw === 'string' ? pkRaw.trim() : '');\n    if (!/^\\\\d+$/.test(pk)) throw new Error(label + ' returned malformed post row');\n    return { pk };\n  }\n  function assertOkStatus(payload, label) {\n    if (!payload || typeof payload !== 'object' || payload.status !== 'ok') {\n      throw new Error(label + ' returned no success evidence');\n    }\n  }","sourceCodeStart":14,"sourceCodeEnd":50,"githubUrl":"https://github.com/jackwener/OpenCLI/blob/49907e53dc3ade5c223ff0c4c2c2785687cec4e6/clis/instagram/comment.js#L14-L50","documentation":"readInstagramJson wraps response.json(); when the response body cannot be parsed as JSON it rethrows '${label} returned invalid JSON'. This catches Instagram returning HTML (login pages, challenge pages) or empty bodies instead of the expected JSON API payload.","triggerScenarios":"A fetch (feed-by-username or comment add) resolves ok but the body is HTML — e.g. a login redirect page, consent/challenge interstitial, rate-limit HTML, or an empty 204-style response passed to res.json().","commonSituations":"Expired session cookies so IG serves the login page; account flagged for verification showing a challenge page; HTML error pages served during outages or heavy rate limiting.","solutions":["Re-authenticate / refresh Instagram session cookies so responses are API JSON, not login HTML","Check the raw response text and Content-Type; if HTML, a login or challenge is being served","Retry after backoff if the failure is transient (rate limiting/outage)","Confirm the request path/headers (X-IG-App-ID, credentials: 'include') are intact"],"exampleFix":"// before\nasync function readInstagramJson(response, label) {\n  try { return await response.json(); }\n  catch { throw new Error(label + ' returned invalid JSON'); }\n}\n// after\nasync function readInstagramJson(response, label) {\n  const text = await response.text();\n  try { return JSON.parse(text); }\n  catch {\n    if (/login|challenge/i.test(text.slice(0, 500))) throw new Error(label + ': session expired, re-login required');\n    throw new Error(label + ' returned invalid JSON: ' + text.slice(0, 200));\n  }\n}","handlingStrategy":"try-catch","validationCode":"const res = await fetch(url, opts);\nconst ct = res.headers.get('content-type') || '';\nif (!ct.includes('application/json')) {\n  throw new Error('Expected JSON, got ' + ct + ' - session probably expired');\n}","typeGuard":"function isJsonResponse(res) {\n  return (res.headers.get('content-type') || '').includes('application/json');\n}","tryCatchPattern":"try {\n  await runCommentPipeline(args);\n} catch (e) {\n  if (/returned invalid JSON/.test(e.message)) {\n    console.error('Instagram returned non-JSON (login/challenge page) - refresh cookies');\n  } else throw e;\n}","preventionTips":["Refresh session cookies regularly","Watch for HTML login/challenge pages served with 200","Add content-type checks before res.json()","Back off on repeated failures - may be rate limiting"],"tags":["instagram","json-parse","invalid-response","session"],"backgroundTag":"invalid-json-response","analyzedSha":"49907e53dc3ade5c223ff0c4c2c2785687cec4e6","analyzedAt":"2026-08-29T08:14:47.543Z","schemaVersion":2},"datasetVersion":"2026-08-29T12:17:43.993Z"}