Skip to content

Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia

feat: format JSON responses having `text/plain` content type (#4916)

Anwarul Islam9e541a8a4b2c
diff --git a/packages/hoppscotch-common/src/helpers/lenses/jsonLens.ts b/packages/hoppscotch-common/src/helpers/lenses/jsonLens.ts
index 0dd96dfa9..30525ed3f 100644
--- a/packages/hoppscotch-common/src/helpers/lenses/jsonLens.ts
+++ b/packages/hoppscotch-common/src/helpers/lenses/jsonLens.ts
@@ -1,6 +1,31 @@
import { defineAsyncComponent } from "vue"
-import { isJSONContentType } from "../utils/contenttypes"
import { Lens } from "./lenses"
+import { isJSONContentType } from "../utils/contenttypes"
+
+/**
+ * Checks if response body contents can be parsed as valid JSON
+ */
+export function isValidJSONResponse(contents: string | ArrayBuffer): boolean {
+ if (!contents) {
+ return false
+ }
+
+ const resolvedStr =
+ contents instanceof ArrayBuffer
+ ? new TextDecoder("utf-8").decode(contents)
+ : contents
+
+ if (!resolvedStr.trim()) {
+ return false
+ }
+
+ try {
+ JSON.parse(resolvedStr)
+ return true
+ } catch (e) {
+ return false
+ }
+}
const jsonLens: Lens = {
lensName: "response.json",
diff --git a/packages/hoppscotch-common/src/helpers/lenses/lenses.ts b/packages/hoppscotch-common/src/helpers/lenses/lenses.ts
index 74ca0246d..c0d8cee3f 100644
--- a/packages/hoppscotch-common/src/helpers/lenses/lenses.ts
+++ b/packages/hoppscotch-common/src/helpers/lenses/lenses.ts
@@ -1,5 +1,5 @@
import { HoppRESTResponse } from "../types/HoppRESTResponse"
-import jsonLens from "./jsonLens"
+import jsonLens, { isValidJSONResponse } from "./jsonLens"
import rawLens from "./rawLens"
import imageLens from "./imageLens"
import htmlLens from "./htmlLens"
@@ -45,6 +45,16 @@ export function getSuitableLenses(response: HoppRESTResponse): Lens[] {
if (!contentType) return [rawLens]
+ // Check if the response content type includes `text/plain` and the body contains valid JSON
+ if (
+ contentType.value.includes("text/plain") &&
+ response.type === "success" &&
+ isValidJSONResponse(response.body)
+ ) {
+ // Append JSON lens to the list of lenses
+ return [rawLens, jsonLens]
+ }
+
const result = []
for (const lens of lenses) {
if (lens.isSupportedContentType(contentType.value)) result.push(lens)