Check if the data is in JSON format or a string before executing any logic based on that information

Is it possible to identify whether the server has returned JSON data or just a string?

If so, how can I parse the JSON and display each element in a loop, or simply display the string.

I envision achieving something like this:

  • Send a POST request with some data

  • If the post bodyText contains curly braces ( { and } ), treat it as JSON and create <li> elements in HTML

Otherwise,

  • just print the bodyText as is.

new Vue({
    el: '#app',
    data: {

            user: {
                UserLogin: 'test',
                UserEmail: 'test',
                UserPassword: 'test'
            },
            responseArr: []
        },
    methods: {
        submit() {
            this.$http.post('http://api.com/validate', this.user)
            .then(response => {
                return "OK";
            },
            error => {  
                    return error.bodyText; 
            })
            .then(data => {
                console.log(data);

                if (data.includes("{")) {
                    console.log("if");
                    data = JSON.parse(data);
                    const arr = [];
                    for (let key in data) {
                        arr.push(data[key]);
                    }
                    this.responseArr = arr;
                }
                else
                {
                    console.log("else");
                    const arr = [];
                    arr.push(data);
                    this.responseArr = arr;
                }
            }
            );
        },
    }
    });

<div id="errorList">
    <li v-for="element in responseArr">
        <div v-if="responseArr.includes('{')">
            <ul class="errorScope">
                <li v-for="nested_element in element">{{nested_element}}</li>
            </ul>
        </div>
        <div v-else>
             <li>{{element}}</li>
        </div>
<button v-on:click="submit">Submit</button>

Answer №1

When dealing with response parsing, it's important to note that the response is always in string format. The challenge lies in determining whether the response is a plain string or if it is meant to be parsed. In such cases, you have two options to consider.

...
.then(response => {
  let type = 'json'
  let data
    try {
      // try to parse the response text
      data = JSON.parse(response)
    } catch {
      // if response is not parseable
      data = response
      type = 'string'
    }
    // now you can distinguish the type of data
})

Alternatively, depending on the library used for $http calls, you may have the option to determine the response type directly (e.g., 'text/plain' or 'application/json').

PS: To verify if the response has been parsed already, you can perform the following check:

if (response instanceof Object) {
  // response is already parsed as a json string,
  // indicating an object or array
} else {
  // response is not yet parsed,
  // consider parsing it further
}

Answer №2

To check whether a value is a JavaScript object or not, you can utilize the typeof operator --

let obj = {'name' : 'John'};
if(typeof obj == "object"){
   // It's an object
}else if(typeof obj == 'string'){
   // It's a string
}

Answer №3

Here is a possible solution:

// HTML
<div id="app">
  <h2>Tasks:</h2>
  <ol>
    <input type="button"
          v-on:click="load()" value="load next">
    <h1 v-if="textResponse">{{textResponse}}</h1>
    <h1 v-if="loadNr==1" style="font-size: 0.8em">click again to load JSON}</h1>
    <li v-for="task in tasks">
      <label>
        <input type="checkbox"
          v-on:change="toggle(task)"
          v-bind:checked="task.done">
        <del v-if="task.done">
          {{ task.text }}
        </del>
        <span v-else>
          {{ task.text }}
        </span>
      </label>
    </li>
  </ol>
</div>

// CSS
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

// JavaScript

const requestText = 'request returned a text response';
const requestJson = '[{"text":"Learn JavaScript","done":false},{"text":"Learn Vue","done":false},{"text":"Play around in JSFiddle","done":true},{"text":"Build something awesome","done":true}]';

new Vue({
  el: "#app",
  data: {
    tasks: [],
    textResponse: '',
    loadNr: 0
  },
  methods: {
    toggle: function(task){
        task.done = !task.done
    },
    load: function(){
        let requestResponse;
      this.textResponse = '';
        if (!this.loadNr) {
        // simulate text
        requestResponse = requestText;
      } else {
        //  simulate JSON
        requestResponse = requestJson;
      }

      let json;
      try {
        if (typeof requestResponse === 'object') {
            //  server sent already parsed JSON
            this.tasks = requestResponse;
        } else {
            //  server sent JSON string
            this.tasks = JSON.parse(requestResponse);
        }
      } catch (error) {
        this.textResponse = requestResponse;
      }
      this.loadNr++;
    }
  }
});

Example Fiddle

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What does the error message "unsupported command-line flag" in Chrome mean for Protractor?

Recently jumping on the Protractor bandwagon, I found myself facing an issue while running my tests on Chrome (an error message appears below the address bar in the browser): A worrisome warning popped up saying something about '--ignore-certificat ...

How can I display a popup window within an iframe on a separate full page?

I am facing an issue while creating an HTML table using AngularJS with a popup. The problem is that I want the popup window, which shows a graph, to open up on the entire page instead of in a specific div. My desired output should look like this: https://i ...

Is it possible to verify whether a function contains a call to another function within it?

Consider a scenario in which we have the following nested functions: function function1(n) { function function2() { function function3() { function function4() { return n * 2; } return function4() } return ...

"Populate a div with an array of images extracted from a JSON file

I found a website that provides an array of images like the sample below. { "imageUrl":"http://server06.amobee.com/aspx/nadav/test/banner320x50.png", "expandedImageUrl":"http://server06.amobee.com/aspx/nadav/test/banner320x320.jpg" } My ob ...

Welcome to the awe-inspiring universe of Typescript, where the harmonious combination of

I have a question that may seem basic, but I need some guidance. So I have this element in my HTML template: <a href=# data-bind="click: $parent.test">«</a> And in my Typescript file, I have the following code: public test() { alert( ...

can a computed property be delayed in its calculation?

Within the code snippet below, we can see that in the compPropsIsBtnDigitizePolygonDisabled function, it initially checks if the digitizePolygonInteractions variable is initialized. If it is not initialized, an error will be triggered. During execution, w ...

Convert JSON data into an HTML table with custom styling

If you have a set of JSON data that you want to convert into an HTML table, you can use the following code: $.each(data, function(key, val) { var tr=$('<tr></tr>'); $.each(val, function(k, v){ $('<td>' ...

Is there a way to enhance the search feature by incorporating a for loop to iterate through data.games and display the corresponding score when a search is made?

$(document).ready(function(){ var searchTerm = "XYZ"; var totalScores = 0; $.ajax({ dataType: 'jsonp', //data in jsonp contentType: "application/json; charset=utf-8", url: 'http://live.nhle.c ...

How to build a flexible gridlist in VUEJs

I've recently become intrigued by VueJs and am on the lookout for a straightforward method to create a dynamic gridlist in VUEJs featuring firstName, lastName, and images for each person. Here's what I attempted, and here's how it turned ou ...

Unable to locate the Shadcn error module: Error encountered when trying to resolve the path '@/components/ui/accordion' within the directory 'Desktop/sadcn/src'

I'm encountering an issue with my Shadcn setup in a simple React app with TypeScript. The error message I'm getting is: Module not found: Error: Can't resolve '@/components/ui/accordion' in '/home/vinayak/Desktop/sadcn/src&ap ...

What is the best way to check the functionality of the front-end across a range of web pages?

I was curious about: Programs capable of performing this task. The specific technology required for this task. If there are any programming languages that could simplify this task. Edit: Provided some answers and tools that might be beneficial to ...

A Guide to Assigning Selected Dropdown Value to Object in Vue

In the image provided, I have a dropdown: https://i.sstatic.net/JWSYM.png The options in this dropdown are retrieved from fetched data: "data": { "type": "products", "id": "2021-01-04.1.1", .. ...

What is the method for applying the action (hide) to every table cell that doesn't include a specific string in its ID?

I have a table with cells containing unique IDs such as "2012-01-01_841241" that include a date and a number. My goal is to filter the table to only display three specific numbers by sending a request and receiving those numbers. Is there a more efficien ...

Utilizing Ajax to dynamically update the values of two PHP variables in real-time, retrieved from an external source

Here is the HTML snippet I am working with: <form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST"> <input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/> <button id="addtowatchli ...

How can Bootstrap-Vue showcase an SVG image as a navigation item?

I need help positioning the Octocat image on the top right corner of a NavBar: In the Vue Snippet below, the icon is currently only visible if there is text inside the <b-nav-item>: <template> <div> <b-navbar toggleable="lg ...

My ability to click() a button is working fine, but I am unable to view the innerHTML/length. What could be the issue? (NodeJS

Initially, my goal is to verify the existence of the modal and then proceed by clicking "continue". However, I am facing an issue where I can click continue without successfully determining if the modal exists in the first place. This occurs because when I ...

Encountering a 404 Error on Vite-Vue Page Hosted on Azure Blob Storage

My website was successfully deployed on Azure blob storage using the Azure Storage Extension for VS code. I navigated to my project folder, clicked on the Azure Section, Storage Accounts, Blob Containers, and then Deployed to Static Website via Azure Stora ...

The Vue instance is referencing the property or method "isCompleted" during render, but it has not been defined

I am currently working on implementing a button that changes color when clicked and toggles the value of isCompleted between true and false. However, I seem to be encountering an issue. I attempted changing 'checkCompleted' to 'checkComplete ...

Display the user's input value in a tooltip without using jQuery

I am looking to achieve this particular layout design. https://i.stack.imgur.com/p9UTH.jpg I am unsure about how to display the input value in the bubble within this layout. The visibility of the bubble should only be triggered on hover. Below is the cod ...

JavaScript promises to resolve and reject

I am currently working on developing a mobile application using NativeScript. I have created an authorization class with a login() function that contains the following code: export default class NitsEditorAuth { //Finding logged-in user. isLoggedI ...