Check if a body is JSON.
npm install @koa/is-jsonimport { createReadStream } from 'node:fs'
import isJSON from '@koa/is-json'
isJSON({ message: 'hello' }) // true
isJSON([1, 2, 3]) // true
isJSON('hello') // false
isJSON(Buffer.from('hello')) // false
isJSON(createReadStream('file.txt')) // false
isJSON(null) // false
isJSON(1n) // trueCommonJS:
const { isJSON } = require('@koa/is-json')isJSON returns true for truthy values, except strings, buffers, and values
with a callable pipe property. It returns false otherwise.
Use JsonValue for JSON data: strings, numbers, booleans, null, and arrays or
objects containing those values.
Use Jsonifiable when your data also contains values with a toJSON method,
such as Date objects.
Use JsonBody for a body that could be Jsonifiable, a buffer, a readable
stream, or an object with a callable pipe method. A value with this type can
still return false from isJSON.
import { Buffer } from 'node:buffer'
import type { JsonValue, Jsonifiable, JsonBody } from '@koa/is-json'
const value: JsonValue = { message: 'hello', count: 2 }
const serializable: Jsonifiable = { createdAt: new Date() }
const body: JsonBody = Buffer.from('hello')The package also exports JsonPrimitive, JsonObject, and JsonArray for
individual JSON shapes, and PipeableBody for objects with a callable pipe
method.
Moving from koa-is-json to @koa/is-json is low effort.
Replace koa-is-json with @koa/is-json in your dependencies.
koa-is-jsonassigns the function tomodule.exportswhere@koa/is-jsonships named and default exports.
so just do this:
-const isJSON = require('koa-is-json')
+const { isJSON } = require('@koa/is-json')ESM callers are unaffected: import isJSON from '@koa/is-json' still works.