Printing JSON data member into console with angular.js - json

I want to access JSON object member using angularjs. I can print the whole json object array but can't access the member of the object uniquely.
$scope.rows = []; // init empty array
$scope.datainput =[];
$http({
method: 'GET',
url: 'Data/input.json'
}).then(function (data){
$scope.datainput=data;
//console.log($scope.datainput);
console.log($scope.datainput);
},function (error){
console.log("big error");
});
var json=JSON.parse($scope.datainput);
console.log(json[0].status);
I have tried this code also but still geting the same error .
$scope.temp = "";
$scope.rows = []; // init empty array
$scope.datainput =[];
$http({
method: 'GET',
url: 'Data/input.json'
}).then(function (data){
$scope.datainput=data;
//console.log($scope.datainput);
console.log($scope.datainput);
var json=JSON.parse($scope.datainput);
console.log(json[0].status);
},function (error){
console.log("big error");
});
json file input.json:
[
{"status":"payfail","value":"310"},
{"status":"payinit","value":"100"},
{"status":"paysuccess","value":"200"},
{"status":"payreturn","value":"50"}
]
I get this error :
SyntaxError: Unexpected end of JSON input
at JSON.parse ()
The solution will be this....
$scope.rows = []; // init empty array
$scope.datainput =[];
$http({
method: 'GET',
url: 'Data/input.json'
}).then(function (data){
$scope.datainput=data.data;
//console.log(data);
console.log($scope.datainput);
var json=JSON.parse(JSON.stringify($scope.datainput));
console.log(json[0].status);
},function (error){
console.log("big error");
});

My guess would be that you are trying to parse the JSON string before it has been returned by the promise.
Try putting your parsing code inside the then block so that it executes in the correct order.
Upon further investigation, here is an updated Answer:
In addition to fixing the promise execution order, it turns out there is an issue with the way that you are accessing the data on the response variable.
Check the documentation for $http here: W3Schools.com $http doco
You will see that the callback response value actually contains a member called data for the response payload. To get this working try accessing the data member on the response object.
$scope.datainput=data.data;
It would probably be a good idea to also rename the data response object from data to response for readability.

You can use this code to solve that:
$scope.rows = []; // init empty array
$scope.datainput =[];
$http({
method: 'GET',
url: 'Data/input.json'
}).then(function (data){
$scope.datainput=data.data;
console.log($scope.datainput);
var json= angular.fromJson($scope.datainput);
console.log(json[0].status);
},function (error){
console.log("big error");
});
You should'n write Json.Parse out function Get you should write this code inside the then block and use data.data to get the data from json file.

Related

Wrong data format for store loadData method ExtJS

I want to call JSON data as much as the amount of data in the store. Here is the code:
storeASF.each(function(stores) {
var trano = stores.data['arf_no'];
Ext.Ajax.request({
results: 0,
url: '/default/home/getdataforeditasf/data2/'+trano+'/id/'+id,
method:'POST',
success: function(result, request){
var returnData = Ext.util.JSON.decode(result.responseText);
arraydata.push(returnData);
Ext.getCmp('save-list').enable();
Ext.getCmp('cancel-list').enable();
},
failure:function( action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Error!', obj.errors.reason);
}else{
Ext.Msg.alert('Warning!', 'Server is unreachable : ' + action.response.responseText);
}
}
});
id++;
});
storeARF.loadData(arraydata);
StoreASF contains data[arf_no] which will be used as a parameter in Ajax request url. StoreASF could contain more than one set of the object store, so looping is possible. For every called JSON data from request would be put to array data, and after the looping is complete, I save it to storeARF with the loadData method.
The problem is, my data format is wrong since loadData can only read JSON type data. I already try JSON stringify and parse, but couldn't replicate the data format. Any suggestion how to do this? Thank you.
Rather than using Ext.util.Json.decode(), normalize the data in success() method using your own logic. For example:
success: function (response) {
console.log(response);
var myData = [];
Ext.Array.forEach(response.data, function (item) {
myData.push({
name: item.name,
email: item.email,
phone: item.phone
});
});
store.load();
}

Weird JSON, how to access needed value

This is the JSON response:
I need to access data[1], which is 0.2. How do I get it?
Here's the actual code:
function getTheValue(){
var result = $.ajax({ url: "https://www.blahblah.com/json" });
return result;
}
console.log(getTheValue());
Here's another way I tried, no luck:
var val = getTheValue();
console.log(val.responseJSON.dataset.data[0][1]);
Your getTheValue function is not returning the JSON response from the AJAX call. It is returning a promise object, since it is actually a doing an asynchronous call. I suggest you read documentation for jQuery.ajax() for more information.
Anyway, you can fix your problem by doing this:
var val;
getTheValue().done(function(response) {
val = response.dataset.data[0][1];
});
The response you're seeing is the ajax object, not the return from the function. $.ajax is asynchronous, so the value isn't available until immediately.
Adapted from the jQuery docs:
$.ajax({
url: your_url,
})
.done(function( result ) {
console.log( result );
});
will give you result. Your subsequent code will need to be triggered inside that done() function.
This finally helped me:
var tBill = getTheBill();
function getTheBill(){
var result;
$.ajax
({
url: "https://www.blahblah.com/json",
context: document.body,
async: false
}).done(function(val) {
result = val;
});
return result.dataset.data[0][1];
}
Guys, thanks for your help! jimm101, you rock.
That object isn't json in its common sense but an Javascript object, if you want the ajax result you have to use a callback:
$.ajax({
url: "https://www.blahblah.com/json" ,
dataType: "json",
})
.done(function(data) {
console.log(data);
});

JSON deserialization with angular.fromJson()

Despite from the AngularJS documentation for angular.fromJson being spectacular, I still don't know how to use it to its fullest potential. Originally I have just been directly assigning the JSON data response from an HTTP request to a $scope variable. I've recently noticed that Angular has a built-in fromJson() function, which seems like something I'd want to use. If I use it, is it safer and can I access data elements easier?
This is how I've been doing it:
$http({
method: 'GET',
url: 'https://www.reddit.com/r/2007scape.json'
}).then(function success(response) {
var mainPost = response; // assigning JSON data here
return mainPost;
}, function error(response) {
console.log("No response");
});
This is how I could be doing it:
$http({
method: 'GET',
url: 'https://www.reddit.com/r/2007scape.json'
}).then(function success(response) {
var json = angular.fromJson(response); // assigning JSON data here
return json;
}, function error(response) {
console.log("No response");
});
It is pointless to convert the response to json as angular does it for you. From angular documentation of $http:
Angular provides the following default transformations:
Request transformations ($httpProvider.defaults.transformRequest and $http.defaults.transformRequest):
If the data property of the request configuration object contains an object, serialize it into JSON format.
Response transformations ($httpProvider.defaults.transformResponse and $http.defaults.transformResponse):
If XSRF prefix is detected, strip it (see Security Considerations section below).
If JSON response is detected, deserialize it using a JSON parser.

Angular $http service - force not parsing response to JSON

I have a "test.ini" file in my server, contain the following text:
"[ALL_OFF]
[ALL_ON]
"
I'm trying to get this file content via $http service, here is part of my function:
var params = { url: 'test.ini'};
$http(params).then(
function (APIResponse)
{
deferred.resolve(APIResponse.data);
},
function (APIResponse)
{
deferred.reject(APIResponse);
});
This operation got an Angular exception (SyntaxError: Unexpected token A).
I opened the Angular framework file, and I found the exeption:
Because the text file content start with "[" and end with "]", Angular "think" that is a JSON file.
Here is the Angular code (line 7474 in 1.2.23 version):
var defaults = this.defaults = {
// transform incoming response data
transformResponse: [function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
data = data.replace(PROTECTION_PREFIX, '');
if (JSON_START.test(data) && JSON_END.test(data))
data = fromJson(data);
}
return data;
}],
My question:
How can I force angular to not make this check (if (JSON_START.test(data) && JSON_END.test(data))) and not parse the text response to JSON?
You can override the defaults by this:
$http({
url: '...',
method: 'GET',
transformResponse: [function (data) {
// Do whatever you want!
return data;
}]
});
The function above replaces the default function you have posted for this HTTP request.
Or read this where they wrote "Overriding the Default Transformations Per Request".
You can also force angular to treat the response as plain text and not JSON:
$http({
url: '...',
method: 'GET',
responseType: 'text'
});
This will make sure that Angular doesn't try to auto detect the content type.

JSON nested object post to node.js server?

I want to POST an Object via JSON to node.js server.
The Object structure is nested, and never succeeded to receive and parse correctly on node.js server site.
EDIT2
I found a solution: see the answer section...
EDIT
I found
console.log(body);
itself output
val1=hello&val2%5Bval3%5D=world
//= {"val1":"hello","val2[val3]":"world"}
weired JSON way
client.js
var data ={val1:"hello",val2:{val3:"world"}};
console.log(data); // -> *1
$.ajax({
url:"/",
type:"POST",
dataType: 'json',
data:data,
success:function (res)
{
resHandler(res);
}
});
*1 ChromeDevelopersTool
Object
val1: "hello"
val2: Object
val3: "world"
server.js
var onreq = function (req, res)
{
if(req.method == 'POST')
{
var body = '';
req.on('data', function (data)
{
body += data;
});
req.on('end', function ()
{
var json = qs.parse(body);
console.log(json.val1); //hello
console.log(json.val2); //undefined
console.log(json.val3); //undefined
console.log(JSON.stringify(json));
//{"val1":"hello","val2[val3]":"world"}
});
}
I understand
val2[val3]
is
val2.val3
However,
Problem 1
JSON.stringify prints out
{"val1":"hello","val2[val3]":"world"}
not
{val1:"hello",val2:{val3:"world"}}
It's ugly, and I don't know why it's like that.
Problem 2
I can never get {val3:"world"}
console.log(json.val3); //undefined
Anyone can explain, and how can I POST a nested JSON to node.js server?
Thanks.
Do NOT use JSON typed data on jQuery Ajax, instead use Stringified JSON
I created a WIKI
http://code.google.com/p/kenokabe/wiki/nestedJSONproblem