Determine whether data is json or string and perform logic basing o that
Clash Royale CLAN TAG#URR8PPP
Determine whether data is json or string and perform logic basing o that
Basically I'm trying to determine whether server returned json or just string
and then convert that json and display its every element in loop or just display that one string.
I'd want to reach something like that:
Send post request with some data
If post bodyText contains and then parse it as json and draw <li>
in html
<li>
else
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>
JSON.parse()
@Pointy I tried that in "previous versions" but at the end for some reason I'm still unable to inject data into html properly. e.g vue ain't refreshing it.
– UbuntuCore
Aug 6 at 13:00
Instead of
data.includes("{")
you can do if (typeof data === "string")
means you got string and do JSON.parse(data)
in if block– Javascript Lover - SKT
Aug 6 at 13:00
data.includes("")
if (typeof data === "string")
JSON.parse(data)
@JavascriptLover-SKT this part works properly, but for some reason displaying has problem with " Property or method "element" is not defined on the instance but referenced during render. " in <div v-else> <li>element</li> </div>
– UbuntuCore
Aug 6 at 13:04
3 Answers
3
Before you parse the response, the response is always string. Problem is you don't know the response is ordinary string, or it is intended to be parseable string. So, you have two options. First, something like this:
...
.then(response =>
let type = 'json'
let data
try
// try to parse the response text
data = JSON.parse(response)
catch
// no, response is not parseable
data = response
type = 'string'
// here you know the type
// and your data are prepared
)
Or, you have second option based on your library you are using for $http calls. Maybe this library can tell you the response type, wheteher it is 'text/plain', or 'application/json'.
PS: If you are unsure if response is already parsed, you can check it this way:
if (response instanceof Object)
// response is already parsed json string,
// so object or array
else
// response is not parsed,
// try to parse it or what
You can use typeof operator to determine if something is Javascript object or not --
let obj = 'age' : 30;
if(typeof obj == "object")
// It's object
else if(typeof obj == 'string')
// It's String
Below is one way of doing it
// HTML
<div id="app">
<h2>Todos:</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="todo in todos">
<label>
<input type="checkbox"
v-on:change="toggle(todo)"
v-bind:checked="todo.done">
<del v-if="todo.done">
todo.text
</del>
<span v-else>
todo.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:
todos: ,
textResponse: '',
loadNr: 0
,
methods:
toggle: function(todo)
todo.done = !todo.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.todos = requestResponse;
else
// server sent json string
this.todos = JSON.parse(requestResponse);
catch (error)
this.textResponse = requestResponse;
this.loadNr++;
);
Sample Fiddle
Server cannot send already parsed json.
– Vladislav Ladicky
Aug 6 at 14:05
What i meant by that is that the api/service that provides the data and sits in between the server and frontend can return json. I rarely deal with json strings. Its almost always json object because thats how intermediate api services are made.
– Rainer Plumer
Aug 6 at 15:19
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You could just call
JSON.parse()
and catch an exception if one is thrown.– Pointy
Aug 6 at 12:58