Json Output display from webservice call - json

I am pretty new to JSON / Jquery world so please bear with my ignorance.
I am trying to read an output from a Json data returned by webservice call like below :
My webservice call is here:
http://example.com/getPortfolioListByContact.json?component=C1&contactId=510297
This return the data as :
{
"data": [
{
"PORTFOLIO_ID": 13495,
"SUBSCRIPTION_ID": 1653,
"STATUS": "ACTIVE",
}
],
"success": true
}
Now I am trying to get alert onthe Json Data returned as string and also want to get this as Parsed /
<script>
var parsed ;
$.getJSON("http://example.com/getPortfolioListByContact.json?component=C1&contactId=510297", function(data){
alert(data.SUBSCRIPTION_ID);
});
parsed = JSON.parse(data);
alert(parsed) ;
</script>
I am getting the response in Alert as "Undefined" . I may not be doing right handling the success handler . I want to get each value and specific value of the json data returned.
Please help.
Thanks

I am getting the response in Alert as "Undefined".
Reason : You are trying to parse the API response out of the scope. As data object is only accessible in the promise returned by the API call.
Try this hope it will work as per your expectation :
$.getJSON("http://example.com/getPortfolioListByContact.json?component=C1&contactId=510297", function(res) {
var data = res.data;
alert(JSON.stringify(data));
});

You are calling data out side the scope.
<script>
var parsed ;
var myData;
$.getJSON("http://example.com/getPortfolioListByContact.json?component=C1&contactId=510297", function(data){
myData = data;
alert(data.SUBSCRIPTION_ID);
});
parsed = JSON.parse(myData);
alert(parsed) ;
</script>

Related

Parsing JSON object sent through AJAX in Django

This is my code creating a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
itemCode : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now the json object looks like:
[{"itemcode":"code1","itemquantity":"quantity1"},{"itemcode":"code2","itemquantity":"quantity2"},...]
My question is how do I parse this data in Django view?
Following is my AJAX function for reference:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: JSON.stringify(items),
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Since I'm sending multiple AJAX request to the same view, I need the 'calltype' data as well.
Thanks you on your answer!! BTW, I badly need to know this simple stuff, which I'm missing
This is my code snippet for parsing:
if (calltype == 'save'):
response_data = {}
bill_data = json.loads(request.POST.get('bill_details'))
itemcode1=bill_details[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
The error being raised is
string indices must be integers
Request your help
For your reference, this is my POST response (taken from traceback):
bill_details = '[{"itemCode":"sav","itemQuantity":"4"}]'
calltype = 'save'
csrfmiddlewaretoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
EDITED Django View
This is my edited view:
if (calltype == 'save'):
bill_detail = request.POST.get('bill_details')
response_data = {}
bill_data = json.loads(bill_detail)
itemcode1=bill_data[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
I fail to understand the problem. SO, to solve it, my question: what is the datatype of the return for get call and what should be the input datatype for json.loads. Bcoz the error being shown is json.loads file has to be string type!! (Seriously in limbo)
Error:
the JSON object must be str, not 'NoneType'

Accessing JSON data from Neo4j REST response in Angularjs

I'm a newbie with rest and angular, so my hope answer to my question is super easy.
I'm having problem working with JSON response I get from new Neo4j post transaction/commit query.
I want to access response data for each item I have in the response. I've searched how others handle this, but have found no same cases. I think I do not parse the response at all, and can not access the specific row.
Here is my code, that just prints all the json.
JS controller
function restcall($scope, $http) {
var call = '{ "statements" : [ { "statement" : "MATCH (n:Cars) RETURN n ORDER BY n.initRank DESC LIMIT 10" } ] }';
$http({
method: 'POST',
url: 'http://myserver:7474/db/data/transaction/commit',
data: call,
})
.success(function (data, status) {
$scope.status = status;
$scope.response = data.results;
})
.error(function (data, status) {
$scope.response = data || "Request failed";
$scope.status = status;
})
};
HTML that just prints out complete response
<section ng-controller="restcall">
<h2>{{status}}</h2>
</br></br>
<h3>{{response}}</h3>
</section>
And most importantly the JSON response I get
{
"results":[{
"columns":[
"n"
],
"data":[
{"row":[{"name":"Car1","initRank":"..."}]},
{"row":[{"name":"Car2","initRank":"..."}]},
{"row":[{"name":"Car3","initRank":"..."}]},
{"row":[{"name":"Car4","initRank":"..."}]},
{"row":[{"name":"Car5","initRank":"..."}]},
{"row":[{"name":"Car6","initRank":"..."}]}]
}],
"errors":[]
}
So basically now I just print out in html my json response.
Now, how do I access individual rows to get i.e. Car3 properties??
I tried the data.results[0][0].data... and also to parse my string, but when I add next .data it just doesn't show a thing, same thing with parsing.. Can someone help please.
Based on that JSON response, you would use data.results[0].data[2].row[0].initRank to access the "initRank" of Car3. You shouldn't need to do any extra parsing of the response. It should already be an object in your callback.

Node.js server : JSON.stringify deep object

Question is simple, but not answered perfectly yet for me (perhaps only for me but is not totaly clear..)
Question : I want to return MongoDB from "collection.findOne" with mongo.. is ok AND JSON.stringify() this informations for send to another service...
// i past a pseudo code for response :-)
collection.find({id_to_find: id_to_find}, function(err, results) {
if (err){
console.log ("error find");
}if (results) { // update for good syntax !
var results = JSON.stringify(results); // error, why ??? <if not this line, is ok, but i want stringify !>
res.json({
returnJSON: results
});
}
}
////////////////////////////////////
// example of a mongo object return :
[ { _id: 1,
property: 'xxxx',
etc: 'xx'
},
{ _id: 2
property: 'xxxx',
etc: 'xxxx'
}
]
Next time, i have severals records like
results_mongo = [{mongo object datas},{ etc.. }] // like an array
i want with my server node.js to JSON.stringify my collection && return theses results..
The error is :::::
TypeError: Converting circular structure to JSON
at Object.stringify (native)
Response ?
(thank to correct object to result, my question is how to exept the stringify deep object.. :)
for searchs, a goods posts on stack :
Convert Mongoose docs to json
How do you turn a Mongoose document into a plain object?
// you are passing object to your stringify method.
var object = JSON.stringify(object);
// you need to pass results as your callack method returns results
var object = JSON.stringify(results);

Issue with getJSON from couchDB SyntaxError: missing ; before statement

SyntaxError: missing ; before statement
{"total_rows":6,"offset":0,"rows":[
Here's my script
function getJSONData() {
var value = [];
var couchDB ="http://X.X.X.X:5984/databasename/_design/name/_view/All%20Content?jsoncallback=?";
$.getJSON( couchDB , function( data ) {
format: "jsonp"
console.log(data);
$.each(data.rows, function(index, row){
value.push(row.value);
});
});
}
How can I get well formed json back from this get request ?
This is happening because your server is returning json data and client is trying to read JSONP fromatted data. you should enable jsonp on couchdb by changing variable allow_jsonp to true under configuration tab.

AngularJS ngResource Send data to server with JSON and get response

In my angular JS app i need to send data to server:
"profile":"OLTP",
"security":"rsh",
"availability":"4",
"performance": {
"TRANSACTION_PER_SEC":1000,
"RESPONSE_TIME":200,
"CONCURRENT_CONNECTION_COUNT":500,
"STORAGE_SIZE":200,
"TOTAL_CONNECTION_COUNT":500
}
and in return i'll get
{"estimate" : 1600,"quoteid" : "Q1234"}
I was trying to do that with $resource but I am lost in syntax.
app.factory("VaaniEstimateService", function($resource) {
var requestURL = "http://128.34.32.34:8080/enquiry";
return $resource(requestURL, {callback: 'JSON_CALLBACK'}, { get: { method:'JSON'}, isArray:false });
});
Can you please provide me something to get me on the right path.
You must use JSONP method and insert JSON_CALLBACK keyword to your url as callback function.
app.factory("VaaniEstimateService", function($resource) {
return $resource("http://128.34.32.34:8080/enquiry?callback=JSON_CALLBACK", {}, {
get: {
method:'JSONP'
},
isArray:false
}).get({
profile:"OLTP",
security:"rsh",
availability:"4",
"performance.TRANSACTION_PER_SEC":1000,
"performance.RESPONSE_TIME":200,
"performance.CONCURRENT_CONNECTION_COUNT":500,
"performance.STORAGE_SIZE":200,
"performance.TOTAL_CONNECTION_COUNT":500
}, function (response) {
console.log('Success, data received!', response);
});
});
Your params will be sent as query params. Angularjs will automatically generate a global function for callback and replace its name with JSON_CALLBACK keyword. Your server must return json as javascript code by calling function that sent with callback parameter. For example, AngularJS is going to make GET request to that url:
http://128.34.32.34:8080/enquiry?callback=angular.callbacks._0?availability=4&performance.CONCURRENT_CONNECTION_COUNT=500&performance.RESPONSE_TIME=200&performance.STORAGE_SIZE=200&performance.TOTAL_CONNECTION_COUNT=500&performance.TRANSACTION_PER_SEC=1000&profile=OLTP&security=rsh
And your server must return response like that:
angular.callbacks._0({"estimate" : 1600,"quoteid" : "Q1234"});
Hope that's enough to give you an idea how jsonp works.