Transforming a json format variable into a javascript array - javascript

I am using the Django framework to build a website.
In the Python file (views.py) I send to the Javascript function an array that has been transformed to json data
Python:
json_data=[1,2,3]
return HttpResponse(json.dumps(json_data), mimetype='application/json')
Then, in Javascript I display the json data in the html.
JavaScript:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
$('.square').append('<p> ' + json_data + ' </p>');});
};
So far everything works. However, I would like to convert the "json_data", which I believe is a string, into an array.
I tried doing this:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
var array = json_data.split(',');
$('.square').append('<p> ' + array[0]+ ' </p>');});
};
Unfortunately, this doesn't work.
Can someone please explain to me what could I do to convert the "json_data" variable into an array in JavaScript?
Thanks a lot.

When you send around data in JSON format it is a string (the main data), but a string formated in such a way that it's easy to recover the data with the original types (ie, your array). Javascript and jquery have different ways to do that. Using jQuery,getJSON is probably the most direct:
http://api.jquery.com/jQuery.getJSON/
You can use your browsers javascript console to see what exactly do your JS variables look like.

"this doesn't work" it's too vague...
Anyway, if I understood your problem, you are dealing with a string, not a JavaScript array... you have to evaluate the data returned from the ajax call:
var theJavaScriptArray = eval('(' + json_data + ')');
or better... use jQuery.ajax and specify json as dataType: jquery doc

In the end, thanks to Zah I discovered the "javascript console", which I didn't know it existed.
I could see that the error was that the "json_data" variable was not a string.
So this is the solution that worked for me:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
var b=json_data.toString().split(',');
$('.square').append('<p> ' + b[0] + ' </p>');
});
};

There is a shorthand in jQuery to parse the json string automatically: jQuery.getJSON()
$.getJSON('/xhr_test/json/', function(data) {
console.log(data); // Here data is already a JavaScript object
});
This is basically the same as:
$.ajax({
url: "/xhr_test/json/",
dataType: "json",
success: function(data) {
console.log(data); // Here data is already a JavaScript object
}
});
Which again is about the same as:
$.ajax({
url: "/xhr_test/json/",
success: function(data) {
var json = $.parseJSON(data); // Here data is a string
console.log(data); // And json is JavaScript object
}
});

Related

NodeJS not able to process array of objects received via POST

I'm having this collection of objects which are inside a html text area:
{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...
...
Is there a way to send the whole collection to node js and iterate through it to get values of objects?
My AJAX code:
$.ajax({
type: "POST",
url: "https://example.com/nodeapp",
data: '['+document.getElementById("list").value+']',
success: function(data) {
console.log(data);
}
});
I tried to do a foreach on req.body, but it doesn't seem to work:
var arr = req.body;
arr.foreach(element=>{
console.log(element.email);
})
Gives the error:
TypeError: arr.foreach is not a function
At first , you have to parse the body by using JSON.parse() function .
Like this :
var arr = JSON.parse(req.body);
arr.forEach(element=>{
console.log(element.email);
});
The javascript's foreach also defined as arr.forEach(...) not arr.foreach(...) .
I found my problem! Incase someone is stuck with the same thing, the whole thing was a string:
'[{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},
{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...]'
Which was considered as one property in JSON which has no value while the server received it. Pretty much like this:
{
"<<the array in string format>>" : ""
}
How I fixed this was, I pushed the objects separately into a new array and sent it to server with JSON content type. (Which was an actual array of objects)

Parse json from php in js

I have array in my php file:
$invoices_arr = [];
foreach ($invoices as $key=>$invoice){
$invoices_arr[$key]['id']=$invoice->get_id();
$invoices_arr[$key]['code_text']=$invoice->get_code_text();
$invoices_arr[$key]['invoice_name']=$invoice->get_invoice_name();
$invoices_arr[$key]['status_invoice']=$invoice->get_status_invoice();
$invoices_arr[$key]['attachments']=$invoice->get_attachments();
}
echo json_encode(['invoices'=>$invoices_arr]);
My ajax call:
$.ajax({
data:{lead_id:$("#lead_id").val()},
url: sJSUrlGetAllLeadInvoices,
success: function (data) {
var obj = jQuery.parseJSON(data);
$("#all_invoice_table tbody").empty();
$(obj.invoices).each(function(key,value){
$('#all_invoice_table').append('<tr><td>'+value.invoice_name+'</td><td class="invoice_status">'+value.status_invoice+'<td>attt</td><td><button id="'+value.id+'" class="edit_invoice_'+value.id+'">Edit invoice</button</td><td><button class="send_invoice_btn_'+value.id+'">Send invoice</button></td><td><img class="delete_invoice_'+value.id+'" src="/images/icons/delete.gif"></td><td class="invoice_hidden_column_'+value.id+'">'+value.code_text+'</td></tr>');
});
}
});
In field value.attachments there is php serialize array, for example, string "a:1:{i:0;s:36:"../../pdf_invoices/2017-10-10015.pdf";}" .
How can I convert this string to array in js?
I try do it:
var mas=JSON.parse(value.attachments);
But I get error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
How can I solve it? Thanks for any help.
Maybe you should unserialize inside PHP code before encode in json
You don't need to parse the result with jQuery.parseJSON because jQuery do it for. If you inspect data using console.log() you will see that is a Javascript object ready for to use.
You need to pass datatype as json.
you can use jQuery parse method for parsing json response.
datatype:json

Trying to store json data into an javascript array

I have the following json data that looks like this...
What I am trying to do is store the temp numbers into a javascript array to display on a graph. This is my code that I was working on...
$.ajax({
type: 'GET',
url: "http://api.openweathermap.org/data/2.5/forecast?q=Redlands,us&mode=json&units=imperial&cnt=20&APPID=5eea63b2ee3505c58713d9149832d4c5",
dataType: 'json',
success: function(data){
//console.log(data.list[0].main.temp);
//trying to parse through data for graph
var date = [];
$.each(data,function(index, data){
date.append(data.list[index].main.temp);
});
}
});
But it is not working I get the following error...
Uncaught TypeError: Cannot read property 'city' of undefined
Anyone know how I can fix this?
i see working , same from Erik Engervall, i change var data for current
$.each(data.list,function(index, current){
date.push(current.main.temp);
});
It seems you're iterating over the entire data object, whereas I believe you only wish to iterate over the data.list:
$.each(data.list, function(index, val) {
date.push(val.main.temp);
});
Also, JavaScript arrays uses push.
Updated answer after Mikel.
You need to use JSON.parse().
var dataList = JSON.parse(data).list;

issue while looping a json array

I retrieve some option for a select from an ajax call in json format.
The code I have set up to display the new options in the select (replacing the existing ones) is the following:
success: function (data){
var $select = $('#dettaglio');
$select.html('');
$.each(data, function(key, val){
$select.append('<option id="' + val.id + '">' + val.text +'</option>');
})
}
while the json is like this:
[
{"id":"1","text":"J-Invest Spa"},
{"id":"2","text":"J-A Holding S.r.l."},
{"id":"3","text":"J-Invest Advisory & Servicing S.r.l."},
{"id":"4","text":"J-Invest Immobiliare e Consulenza S.r.l."}
]
Running this code leads to an error that is not easy to understand:
TypeError: invalid 'in' operand e
...===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in
e)}r=b(o);var _={}...
jQuery is throwing an error but this is not helpful to see where my code is wrong. Any hint?
Yes I get an array from mysql and encode it with json_encode. The data received from the server will always be of string type. You need to parse it to convert to JSON format. Can you try this?
success: function(data) {
data = JSON.parse(data);
Or in case, if you are using some Old IE, you can also try:
success: function(data) {
data = $.parseJSON(data);
The easiest way would be to change a bit on your PHP, by adding this:
header('Content-type: application/json');
Just that. jQuery is automatically set to detect the encoding of the returned data. If later you decide to send something else, you just change the header.
Warning: This function must be one of the first ones to be executed, before ANY output. Otherwise, it will throw errors at you.

How to get JSON from PHP to JS?

I have really been searching for almost 2 hours and have yet to find a good example on how to pass JSON data from PHP to JS. I have a JSON encoding script in PHP that echoes out a JSON script that looks more or less like this (pseudocode).
{
"1": [
{"id":"2","type":"1","description":"Foo","options:[
{"opt_id":"1","opt_desc":"Bar"},
{"opt_id":"2","opt_desc":"Lorem"}],
{"id":"3","type":"3","description":"Ipsum","options:[
...
"6":
{"id":"14","type":"1","description":"Test","options:[
...
etc
Problem is, how can I get this data with JavaScript? My goal is to make a .js script that generates a poll based on these JSON datas, but I honest to god can't find any examples on how to do this. Guessing it is some something like:
Obj jsonData = new Object();
jsonData = $.getJson('url',data,function()){
enter code here
}
Any links to any good examples or similar would be highly appreciated. And I thought that encoding the data in PHP was the tricky part...
EDIT:
I got this code snippet to work, so I can review my whole JSON data in JS. But now I can't seem to figure out how to get to the inner data. It does print out the stage number (1-6) but I can't figure out how to get the question data, and then again the options data within each question. Do I have to experiment with nested each loops?
$(document).ready(function()
{
$('#show-results').click(function()
{
$.post('JSAAN.php', function(data)
{
var pushedData = jQuery.parseJSON(data);
$.each(pushedData, function(i, serverData)
{
alert(i);
})
})
})
});
The idea here is to get into the question information in the middle level and print out the qusetion description, then based on the question type - loop through the options (if any) to create checkbox/radiobutton-groups before going on to the next question. The first number represents which stage of the multi stage poll I am currently working on. My plan is to divide it into 6 stages by hiding/showing various divs until the last page where the form is submitted through Ajax.
Not sure but I think, you can use
$.getJSON('url', data, function(jsonData) {
// operate on return data (jsonData)
});
now you can access and operate on the PHP json data,
if you're going to use it outside the getJson call you can assign it to a variable
var neededData;
$.getJSON('url', data, function(jsonData) {
neededData = jsonData;
});
Try the jQuery documentation: http://api.jquery.com/jQuery.getJSON/
This example should get you started:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
This example is based on the JSON structure being;
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Do not use echo in PHP. It will print string not JSON.
Use json_encode to pass JSON to javascript.
Use can use each to get the values in JSON at javascript end.
Example
http://www.darian-brown.com/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/
If you are using JQuery there is a really simple solution to your approach as you can see here: http://api.jquery.com/jQuery.getJSON/.
Otherwise I just want you to explain that there is no way to access your JSON directly in JavaScript as you tried in your code above. The main point is, that JavaScript runs on your browser while your PHP script runs on your server. So there must definitely be a communication between them. So you have to request the data from the server over http I would suggest.
HTH

Categories