I have the following json response I need to alert errors object through javascript.
{"sEcho":1,"iTotalRecords":1,"iTotalDisplayRecords":1,"aaData":{null},"errors":{"msisdn":"num\u00e9ro de t\u00e9l\u00e9phone non valide"}}
I m newbie with json and I couldn't find a way to alert my error rendered by my controller.
Many Thx
Try this:
// your json data
var s = '{"sEcho":1,"iTotalRecords":1,"iTotalDisplayRecords":1,"aaData":"{null}","errors":{"msisdn":"phone non valide"}}';
// change in json object
var obj = JSON.parse(s);
// get errors value
console.log(obj.errors);
Make sure that you have valid json data.
Try with below code
var j = '{"sEcho":1,"iTotalRecords":1,"iTotalDisplayRecords":1,"aaData":null,"errors":{"msisdn":"num\u00e9ro de t\u00e9l\u00e9phone non valide"}}';
var a = JSON.parse(j);
alert(a.errors.msisdn);
It will display message of msisdn property of errors, as msisdn is child property of errors.
Related
I have this array of objects:
var people = {name:'list 1',mode:0,friends:[{user:1,code:'red'},{user:2,code:'blue'}]};
I want to write it to a file so if the node server crashes I dont lose the data. I did this:
//define variables from file
var file = "../../people.txt";
var open = fs.readFileSync(file);
va data = open.toString();
var name = data.name;
var mode = data.mode;
var friends = data.friends;
whenever a variable changes I save it to a file like this:
function update() {
//dosomething
name = 'new list';
mode = 1;
friends = [{user:4,code:'red'},{user:6,code:'blue'}]
fs.writeFileSync(file,`{name:'${name}',mode:${mode},friends:${friends}'}`,{encoding:'utf8',flag:'w'});
}
This is output onto the file
{name:'list 1',mode:0,friends:[object, object]}
and the data cant be read at all. What am I supposed to do here?
Thank you.
You should convert the JSON data into a string format using JSON.stringify() before writing it to a file, and when reading them out, you should parse the string into JSON using JSON.parse()
More details are here and how to read/write JSON files
I am writing a JavaScipt application and am attempting to fetch data from a certain URL but am getting an undefined value. The expected value after fetching and converting it to json should result in an array. I am not sure why this is happening. I have put my code below:
let promiseResponse = fetch("some-url");
let response = await promiseResponse;
// check if there was an error in fetching the data (no error detected)
if(!response.ok) {
alert("An error occured when attempting to fetch data.")
}
// a console.log statement here for the var 'response' results in "[object Promise]"
let parsedPromiseResonse = response.json();
let parsedResponse = await parsedPromiseResonse;
// printing out the 'parsedResponse' var gives me [object Object]
// printing out the 'parsedResponse[0]' var gives me undefined
EDIT:
For more context, the data to be retrieved in the URL is formatted like this:
{"variants":["some-string","some-string"]}
Any help would be greatly appreciated!
To access the json to have to call the entity variants then access to the items, something like
alert(parsedResponse.variants[0])
And the result should be
some-string
If you are referring to the varients array, then this is how you will get the array values.
parsedResponse["varients"]
For the first index
parsedResponse["varients"][0]
I have been working on this problem for quite a while now.
I am defining an array using the following:
let newJsonObject = {
"billing_name": document.getElementsByName("order[billing_name]")[0].value,
"email": document.getElementsByName("order[email]")[0].value,
};
I get the data from storage and keep it in a variable named parsedJson, then do the three following console.log operations:
console.log(parsedJson);
console.log(parsedJson.billing_name);
console.log(parsedJson["billing_name"]);
This first returns an object with the following:
parameters:
{"billing_name": "123", "email": "123"}
However, the following two things logged in the console are undefined.
I have also tried to create the object with the keys not having quotations, but I am still getting undefined
I don't understand why the log is returning null when the object is defined. Does anyone have any suggestions?
EDIT:
Here is how I am storing the data:
chrome.storage.sync.set({"parameters": JSON.stringify(newJsonObject)});
Here is how I am accessing it:
chrome.storage.sync.get("parameters", params => {
if(params === null){
//Nothing is even set, simply return
return;
}else{
//Actually data saved in params
let parsedJson = params;
console.log(parsedJson);
console.log(parsedJson.parameters.billing_name);
console.log(parsedJson["billing_name"]);
Here is a link to what is displayed in console
use JSON.parse converts your json string to object
try this
console.log(JSON.parse(parsedJson.parameters).billing_name);
Try this:
var test = JSON.parse(parsedJson.parameters);
console.log(test.billing_name);
this will work.
I'm using this code to get a JSON file stored in the same folder.
var schedtotal = 0;
var requestURL11 = 'schedtotal.json';
var request11 = new XMLHttpRequest();
request11.open('GET', requestURL11);
request11.responseType = 'json';
request11.send();
request11.onload = function() {
window.superHeroes11 = request11.response;
populateHeader11(superHeroes11);
}
function populateHeader11(jsonObj) {
window.schedtotal = jsonObj.total;
console.log("populateHeader function has activated");
console.log(jsonObj);
}
The file looks like this:
{"total": 3}
It's valid JSON. I'm trying to extract the value of total using the same exact method that I've used successfully for all the other JSON parsings in the rest of the file (which I have not included here).
When populateHeader11 is called, it doesn't change schedtotal to equal total. It remains at its original setting of 0. The console log returns from the function as having activated and also returns the JSON file so I know it can access it at least.
I've tried changing .jsonObj.total to .jsonObj['total'] and it didn't change anything.
Previous times I've screwed around with this, it has sometimes returned an error saying it can't get 'total' from null. Now it just doesn't return anything in its current state. What is going on?
You need to parse the JSON string into an object before you try and access the total field.
var jsonString = "{\"total\": 3}";
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.total);
I'm using the code below to construct a JSON object that looks like this:
{"contacts":[{"provider":"Yahoo","firstName":"myname","lastName":"surname","nickname":"mynick","email":"myemail#hotmail.com","photoURL":"http://l.yimg.com/dh/ap/social/profile/profile_bxx.png"}]};
var data = {};
var contacts;
var gc = $.when(gigya.socialize.getContacts({callback: function(response){
data['contacts'] = response.contacts.asArray();
}}));
gc.done(function(response) {
contacts = data;
});
console.log(contacts);
When I pass the resulting contacts object to Google soy template, the JSON object doesn't seem well constructed.
With the code above, how do I construct a valid JSON object?
Thanks for helping out.
The object seems ok,
try using JOSN.stringify() example jsFiddle
or JSON.parse()
You can see in example, you can turn object into valid JSON and reverse into valid JS object.
Regarding your code
What do you get from response ?
And why do you use response here if you do not make use of it?
gc.done(function(response) {
contacts = data;
});
I would change this line EDITED
data['contacts'] = response.contacts.asArray();
to
contacts = JSON.parse(response.contacts);
and remove
gc.done(function(response) {
contacts = data;
});