Python Error When Accessing JSON Data From AngularJS POST - javascript

I am trying to send data to a python script via POST but unable to read it. The UI is in AngularJS. I have seen similar questions but they are either not using AngularJS or not using POST.
The Angular code:
$scope.send = function(){
$data = {
"tableData":$scope.personsSelected
}
$postData = JSON.stringify($data);
Services.post('testbed.cgi', $postData);
}
Python Code:
formData = cgi.FieldStorage()
print json.dumps(formData)
Error Message:
TypeError: FieldStorage(None, None, []) is not JSON serializable
I have tried setting the content type to application/x-www-form-urlencoded but to no avail. What am I missing here?

The issue is with the data you are trying to send as JSON. Whats the data you are trying to send? Is it a Python object? This may help you. Are those plain strings? Dictionary? Do they have invalid characters? You can use JSON Lint to check validity.

Related

Flask: python object to json triggering error when read by javascript

I'm trying to pass python dictionaries and javascript objects back and forth as necessary. From similar questions, I've gathered that I need to do this.
Python:
posts = [
{'author':'JL Rowling','title':'Harry Potter'},
{'author':'JRR Tolkien','title':'Lord of the Rings'},
]
Javascript:
var jsonPosts = JSON.parse({{ posts }});
console.log(jsonPosts);
Likewise, these doesn't work either:
var jsonPosts = JSON.parse(posts|tojson);
var jsonPosts = {{ posts|tojson }};
The JS error I'm triggering is TypeError: Object of type Undefined is not JSON serializable
I got this advice from the following Q/A:
Python to Javascript JSON objects (Flask)
How can I pass data from Flask to JavaScript in a template?
How can I fix this?
Edit:
I've used answer recommendation and found the following error to be present in the console:
VM129:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at about:16
Corresponding to
let jsonPosts = JSON.parse();
It seems that it doesn't have access to encoded_posts.
You need to use the encoded posts:
encoded_posts = json.dumps(posts)
That will give you string, which is what JSON.parse is expecting.
var jsonPosts = JSON.parse({{ encoded_posts }});

How to parse a javascript list containing dictionary in python django

I have a webhook.
data0=[{"senderId":"smsdia","requestId":"******383233353233","report":[{"date":"2017-12-02 17:00:41","number":"12345","status":"1","desc":"DELIVERED"}],"userId":"119385","campaignName":"viaSOCKET"}]
I receive the above data in a POST request to my server.
Content-Type: application/x-www-form-urlencoded
How do I parse it?
I know that if it is a list: data1=['sree','kanth'] I can parse it with request.POST.getlist('data1[]')
But I don't know how to parse when it is a list containing dict.
edit1
Moreover, I get len(data1) is 2. But len(data0) is 0.
edit2
using request.lib:
https://requestb.in/13df2891?inspect
This appears to be JSON sent inside a form field. You can use the json library to parse it:
data = json.loads(request.POST['data'])

Get JSON Data from Cherrypy Server with jQuery/AJAX

and python/cherrypy server
#cherrypy.tools.json_out()
#cherrypy.tools.json_in()
def get_data(self):
cherrypy.response.headers['Content-Type'] = 'application/json'
datas = {"ABCDEF"}
return datas
but I get a Internal Server Error (500), where is my mistake?
I get work to post data to server, but with getting data is my problem..
One problem is in your fifth line of your second code block. Change
datas = {"ABCDEF"}
to something like
datas = { "somedata" : "ABCDEF"}
And if this is all of your cherrypy server code, you're not exposing your route. Then you have to add the
#cherrypy.expose
annotation. You can consult the docs for this as well.
Your datas variable is a Python set, and those are not directly serialisable to JSON. Perhaps you meant to create a dictionary or list?

Codeigniter - sending json to script file

I query the db i my model like so
function graphRate($userid, $courseid){
$query = $this->db->get('tblGraph');
return $query->result();
}
My controller gets data back from my model and I json encode it like so
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['graph_json'] = json_encode($query);
}
$this->load->view('graph', $data);
And thats returns me a json object like so
[
{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
]
In my view graph I'm loading an js file
<script type="text/javascript" src="script.js"></script>
Now I want to use $data that is being sent from my controller to my view, to my external script.js to use as labels and data to feed my chart. But How do I get that Json data to my external script.js so I can use it?
1 more thing about the json data, isn't it possible to get the output of the json data as
{
"obj1":{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
"obj2":{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
"obj3":{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
}
The problem isn't a Codeigniter problem, it's a javascript scope/file inclusion/where-do-i-get-my-data-from problem.
I run into this all the time and have used these solutions:
naming my php files with .php extensions and loading them as if they're views.
Just putting the script that needs data from a view IN the view file where it's used
Using an ajax request in my included js file to hit a controller and get json data.
I use #2 most frequently (for things like datatables where I WANT the js code right there next to the table it's referencing.
I use #1 occasionally, but try NOT to do that because it means some .js files are in my webroot/js dir and some are in teh application/views directory, making it confusing for me or anyone else who wants to support this project.
#3 is sometimes necessary...but I like to avoid that approach to minimize the number of requests being made and to try to eliminate totally superfluous requests (which that is).
You need to print the result of the output json string to the html generated file.
But you need to parse the string with some script. I would recommend you: http://api.jquery.com/jQuery.parseJSON/
For the second question. It is possible by doing:
$returnValue = json_encode(
array (
"obj1" => array("id"=>"1","title"=>"myTitle","score"=>"16","date"=>"2013-08-02"),
"obj2" => array("id"=>"2","title"=>"myTitle2","score"=>"17","date"=>"2013-09-02"),
"obj3" => array("id"=>"3","title"=>"myTitle3","score"=>"18","date"=>"2013-10-02"),
)
);
Print the output using PHP like:
echo json_encode($query);
Then from the client-side (where JavaScript resides) load that JSON that you printed using PHP. This can be done easily using JQuery.
Like this:
$.get("test.php", function(data) {
alert("Data Loaded: " + data);
});
You can find more information about this here: http://api.jquery.com/jQuery.get/
Now you'll need to parse this data so that JavaScript can understand what you got as text from the server. For that you can use the JSON.parse method on the "data" object in the aforementioned example. Once parsed, you can use the object like any other object in JavaScript. You can find more information about JSON.parse here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I hope that helps.

Send JSON Object to Rails

Hi I'm new to rails so please bear with me :) I want to send JSON object to rails and save it to database. basically I have a data entered by the user then I have a javascript function thats retrieves the data and convert it into JSON object. What i want is to sent the JSON object maybe through ajax to rails and save it to the database.Can anyone give me any idea how to do it. thnx
function save(){
----(some codes)
notesArray.push({ Index: i, Title: title.val(), Content: content.val()});
// json encode it
var jsonStr = JSON.stringify(notesArray);
//want to add code here to send to rails
}
If you're using jQuery, it's very easy to do this using $.post():
$.post('/some/page/here', {notes: jsonStr});
As to "handle the JSON object in the controllers" you can use parsed_params = CGI.parse(params[:_json]) ,then you can get what you what througt parsed_params[key1][key2]

Categories