JSON nested object post to node.js server? - json

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

Related

Printing JSON data member into console with angular.js

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.

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();
}

AJAX HTTP-POST-Request - Saving JSON responses

I want to make a HTTP-POST-Request with AJAX to call a JSON API. So, the API should return a response in JSON. I can see on the console of the API, that the request is successful. But the problem is, that no data or status is returned, or that I can't use it with JQuery. Here is my function:
$.post("http://api-adress/controller",
{
email: input_mail,
password: input_pw
},
function(data, status){
alert(data);
alert(status);
}, 'json');
I guess the problem is that the response from the Server does not get saved in the variables data and status correctly.
I would suggest to change a little bit your code like below:
var dataString = {
email: input_mail,
password: input_pw
}
$.post("http://api-adress/controller", dataString, function (result) {
})
.done(function (result) {
//Here is your result. You must parseJSON if it is json format
var data = jQuery.parseJSON(result);
})
.fail(function () {
//use this if you need it
})
Also make sure that you get the response through firebug in console tab. You can check there what you post, what you get etc.

Pretty printing JSON to a file in Node

So I have a very large JSON data which I am sending to a node server via AngularJS. This is the procedure I'm using to send data :-
var send_data="data="+encodeURIComponent(JSON.stringify($scope.records,null,4));
$http({
method : 'POST',
url : 'http://localhost:8888/updateDetails',
data : send_data,
responseType : "json",
headers: {
"Content-Type": 'application/x-www-form-urlencoded'
}
}).success(function(data, status, headers, config){
console.log(data);
});
I successfully managed to send a pretty printed JSON to the Node Server via the above code. However when I write this to a file using :-
jsonfile.writeFile(file, JSON.parse(req['body']['data']), function (err) {
console.error(err);
});
After some testing I figured out that the error is in the JSON.parse statement. Any way to pretty print JSON to a file?
Use JSON.stringify(data[, replacer[, indent]]):
jsonfile.writeFile(file, JSON.stringify(JSON.parse(req.body.data), 0, 4), function (err) {
console.error(err);
});
You also may or may not need to parse the response body though -- I believe responseType: "json" in the builder will automatically parse it for you:
jsonfile.writeFile(file, JSON.stringify(req.body.data, 0, 4), function (err) {
console.error(err);
});
Here's a complete working isolated example of how it works:
var fs = require('fs');
var req = JSON.parse('{"body": {"data": "Some text."}}');
fs.writeFile('test.json', JSON.stringify(req.body, 0, 4), function (err) {
});
Assuming you're handling POST requests via an HTTP listener or framework like express? Are you using a body parser to parse the incoming JSON?
Let's try:
console.log(req.body) to make sure your server recognizes the request.
Is it a JSON string? Is it valid? Or is it a javascript object (i.e. already been parsed)?
If it's been parsed, then my second suggestion will work. If it hasn't been parsed, parse it as I did in the first example.

Parse JSON from JQuery.ajax success data

I am having trouble getting the contents of JSON object from a JQery.ajax call. My call:
$('#Search').click(function () {
var query = $('#query').valueOf();
$.ajax({
url: '/Products/Search',
type: "POST",
data: query,
dataType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
for (var x = 0; x < data.length; x++) {
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
$(content).appendTo("#ProductList");
// updateListing(data[x]);
}
}
});
});
It seems that the JSON object is being returned correctly because "alert(data)" displays the following
[{"Id": "1", "Name": "Shirt"}, {"Id": "2", "Name":"Pants"}]
but when I try displaying the Id or Name to the page using:
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
it returns "undefined" to the page. What am I doing wrong?
Thanks for the help.
The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType to just 'json' to have it converted automatically.
I recommend you use:
var returnedData = JSON.parse(response);
to convert the JSON string (if it is just text) to a JavaScript object.
It works fine,
Ex :
$.ajax({
url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "تهران",
type: 'GET',
cache: false,
success: function(result) {
// alert(jQuery.dataType);
if (result) {
// var dd = JSON.parse(result);
alert(result[0].Id)
}
},
error: function() {
alert("No");
}
});
Finally, you need to use this statement ...
result[0].Whatever
One of the way you can ensure that this type of mistake (using string instead of json) doesn't happen is to see what gets printed in the alert. When you do
alert(data)
if data is a string, it will print everything that is contains. However if you print is json object. you will get the following response in the alert
[object Object]
If this the response then you can be sure that you can use this as an object (json in this case).
Thus, you need to convert your string into json first, before using it by doing this:
JSON.parse(data)
Well... you are about 3/4 of the way there... you already have your JSON as text.
The problem is that you appear to be handling this string as if it was already a JavaScript object with properties relating to the fields that were transmitted.
It isn't... its just a string.
Queries like "content = data[x].Id;" are bound to fail because JavaScript is not finding these properties attached to the string that it is looking at... again, its JUST a string.
You should be able to simply parse the data as JSON through... yup... the parse method of the JSON object.
myResult = JSON.parse(request.responseText);
Now myResult is a javascript object containing the properties that were transmitted through AJAX.
That should allow you to handle it the way you appear to be trying to.
Looks like JSON.parse was added when ECMA5 was added, so anything fairly modern should be able to handle this natively... if you have to handle fossils, you could also try external libraries to handle this, such as jQuery or JSON2.
For the record, this was already answered by Andy E for someone else HERE.
edit - Saw the request for 'official or credible sources', and probably one of the coders that I find the most credible would be John Resig ~ ECMA5 JSON ~ i would have linked to the actual ECMA5 spec regarding native JSON support, but I would rather refer someone to a master like Resig than a dry specification.
Try the jquery each function to walk through your json object:
$.each(data,function(i,j){
content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
$('#ProductList').append(content);
});
you can use the jQuery parseJSON method:
var Data = $.parseJSON(response);
input type Button
<input type="button" Id="update" value="Update">
I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below
$(function() {
$('#Search').click(function() {
var query = $('#query').val();
var update = $('#update').val();
$.ajax({
type: 'POST',
url: '/Products/Search/',
data: {
'insert': update,
'query': address,
},
success: function(res) {
$('#ProductList').empty('');
console.log(res);
json = JSON.parse(res);
for (var i in json) {
var row = $('<tr>');
row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
$('</tr>');
$('#ProductList').append(row);
}
},
error: function() {
alert("did not work");
location.reload(true);
}
});
});
});
I'm not sure whats going wrong with your set up. Maybe the server is not setting the headers properly. Not sure. As a long shot, you can try this
$.ajax({
url : url,
dataType : 'json'
})
.done(function(data, statusText, resObject) {
var jsonData = resObject.responseJSON
})
From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON() based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).
Or you can set the dataType to json to convert it automatically.
parse and convert it to js object that's it.
success: function(response) {
var content = "";
var jsondata = JSON.parse(response);
for (var x = 0; x < jsonData.length; x++) {
content += jsondata[x].Id;
content += "<br>";
content += jsondata[x].Name;
content += "<br>";
}
$("#ProductList").append(content);
}
Use
dataType: 'json'
In .NET you could also return Json(yourModel) in your action method/API controller.
And parse the returned JSON as follows in the Jquery .ajax:
if you've a complex object: navigate to it directly.
success: function (res) {
$.each(res.YourObject, function (index, element) {
console.log(element.text);
console.log(element.value);
});
});