why json response has square brackets [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
For some reason I have to use JSON like this:
php code
$json = json_decode([{
"key":1812,
"ticks":0,
"events":"7F7E7F7E7F7E7F7E7F7E7F7E7F7E",
"s1a":"011A00002066C0D9",
"s1c":"011C0149040901496650002830000000000000023344000043410000000300000004C5BD",
"s46":"014600283000CA8D","s10":"011000287182943B",
"s9a":"019A0000000018000000000000000000DC69",
"version" : "18.05"
}]);
// and use $json in loop to populate the table...
that pair of square brackets does not let me do anything with it in php. My editor show an parse error. I solved this problem in js like this:
var data = json[0];
var i;
for(i=0; i<json.length; i++){
var html = '';
html += '<td>' + json[i]["key"] + '</td>'
+ '<td>' + json[i]["ticks"] + '</td>'
+ '<td>' + json[i]["events"] + '</td>'
+ '<td>' + json[i]["s1a"] + '</td>'
+ '<td>' + json[i]["s1c"] + '</td>'
+ '<td>' + json[i]["s46"] + '</td>'
+ '<td>' + json[i]["s9a"] + '</td>'
+ '<td>' + json[i]["version"] + '</td>';
}
$(html).appendTo('#bundle');
//var jsonEncoded = JSON.parse(data);
console.log(json.length);*/
But it seems bad to use it like this. How can I solve this in php?

you can simply use json_decode for this in PHP, Like:
<?php
$data = json_decode($json);
var_dump($data[0]->key);
var_dump($data[0]->events);
And you can access them simply by using the index 0. Demo
Edit: The problem with your code is that your are not enclosing the json string in quotations. You should use it like this:
$json = json_decode('[{
"key":1812,
"ticks":0,
"events":"7F7E7F7E7F7E7F7E7F7E7F7E7F7E",
"s1a":"011A00002066C0D9",
"s1c":"011C0149040901496650002830000000000000023344000043410000000300000004C5BD",
"s46":"014600283000CA8D","s10":"011000287182943B",
"s9a":"019A0000000018000000000000000000DC69",
"version" : "18.05"
}]');

Also worth mentioning that if you are using an ORM, and you are working with collections (which is a common use case with Laravel, for example, and with many other PHP frameworks), there are two ways you can return something that you are looking for in a query.
First: you query an array of elements, and in this case, only one is found. Then, if you pass that as your response, it will contain the array brackets - a valid JSON type.
But if you specifically query for a single element (like with ::first() in the case of Eloquent), if you return that, it will automatically only return the object, without any enclosing brackets.
Edit: seeing your edit, yeah, mega6382 has the answer.

Related

I want to re-generate part of a random generated paragraph created from arrays

I am not entirely sure what to even search to find a solution here, but essentially I have a random text generator that creates a writing prompt from a series of arrays. The behaviour I want to add to it is the ability to "reroll" any of the individual random elements by clicking on them. Here's what the current function looks like that gets returned when the button is clicked.
function art_prompt() {
return (
'<p>' + 'The main character is a ' + get_three_random_words(personality) + ' ' + get_random_word(gender) +
' who ' + get_random_word(frequency) + ' ' + get_random_word(flaws) + ' and ' + get_random_word(frequency) +
' ' + get_random_word(flaws) + '. The character is paired with ' + get_random_word(atmospheres) +
' atmosphere, set ' + get_random_word(places) + ' during ' + get_random_word(time) + '.<br><br>' +
'The scene portrays ' + get_random_word(portrayals) + '.<br><br>' + '<strong>Bonus restriction:</strong> ' +
get_random_word(bonus_restrictions) + '.' + '</p>'
);
}
So essentially, each of the get_random_word(array) functions I want to be a clickable element that generates a new random string from the same array. I have tried something where each one has a button concatenated around it and create a separate function for each array that is being brought in, but I want a more elegant solution if one exists.
Also I realize it's a bit janky of an implementation, but it's all I knew how to do when I started on it.
So I seem to have figured out a working solution. Just wrapped each object in a button, like this:
'<p>' + 'The main character is a ' + '<button onclick="rollPersonality1()" class="reroll personality1">' + personality[rand1] + '</button>, '
Using the buttons is a bit janky but it seemed to do the trick in this instance. I ran into another issue where I was trying to run the onclick function the same way I did for a static button, but it didn't work because the selector outside the function was no good. So the function for the above looks something like this.
var rollPersonality1 = () => {
var PersonalityElement = document.querySelector('.personality1');
PersonalityElement.textContent = randomPersonality();
}
I doubt this will help anybody else, but if it does that's awesome! If anyone has a more elegant way of doing this, I am not super happy with the messiness of what I came up with. So lay it on me!

JavaScript failing when parsing XML that has blanks in nodeValues?

I have an application that uses Javascript to parses a XML array that is returned from a Webservice and iterates through it and builds it into a table body. It has been working with no issues until lately.
We had some changes on the database that the Webservice is returning results from in which now there are a few columns that could potentially have blanks or null values.
The Javascript fails to run when it hits a childNode that has a blank or null value.
Below is a snapshot of the browser error:
So my question is how do I handle those blanks so that the Javascript will just build an empty string into the table body and continue iterating through the xml array?
I have tried to build an if statement into the Javascript in the for loop to replace the blank or null value with '', but I'm not sure it's going to be doable with the way my table body is being built.
for (i = 0; i < x.length; i++) {
tbody += "<tr><td class=col1>" +
x[i].getElementsByTagName("CheckInDate")[0].childNodes[0].nodeValue +
"</td><td class=col2>" +
x[i].getElementsByTagName("CheckOutDate")[0].childNodes[0].nodeValue +
"</td><td class=col3>" +
x[i].getElementsByTagName("CheckInOut")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("address")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("names")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("companyName")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue.substr +
"</td><td>" +
x[i].getElementsByTagName("contactPhoneNum")[0].childNodes[0].nodeValue +
"</td ></tr >";
}
Being as how this is an existing application I don't want to rebuild all the functions that build tables using this method so I hope there is an easy solution to this that I'm not seeing.
The problem is that .childNodes will be null if the XML element doesn't have any content (any text nodes). You seem to have a lot of repeating code, to fix this you can create a function to get the content of an XML node with a specific tag name if it has any content or return an empty string.
Here is an example:
function getElementContent(element, tagName) {
const e = element.getElementsByTagName(tagName);
if (e && e.childNodes && e.childNodes.length) {
return e[0].childNodes[0].nodeValue
}
return '';
}
const tbody = x.map(e => `<tr><td class=col1>${getElementContent(e, 'CheckInDate')}</td><td class=col2>${getElementContent(e, 'CheckInDate')}..... `).join('');

Comparison of two String is not working in script

Actually in my function I have to compare two strings, the one string I fetch through the db and compare to the null string but it's not working..
Here is my Code:
order.items.forEach(function(entry) {
result += '<tr>'
+ '<td>'+'<font size=2>'+ a++ + '</font>'+ '</td>'
+ '<td>' +'<font size=2>'+ entry.title + '</font>'+ '</td>'
+ '<td>' +'<font size=2>'+ entry.quantity + '</font>'+'</td>'
if(entry.personalization == 'null') //here is the problem
+ '<td>' +'<font size=2>'+ 'No Personalization' + '</font>'+'</td>'
else
+ '<td>' +'<font size=2>'+ entry.personalization + '</font>'+'</td>'
+ '</tr>';
})
result +='</table>';
$('.modal-body').html(result);
Use console.log(entry.personalization) to check value.
Dhara's answer should work...
I also use it for null check.
(!entry.personalization)
or try
(entry.personalization != "")
To check empty or null string in jquery:
if (!entry.personalization) {
// is empty
}
As mentioned in your question, if one string i fetched by you and the other string is "null", It is a clear question of string comparison and not checking null...
Javascript has localeCompare() method to compare strings..
You should use
entry.personalization.localeCompare("null");
or its inverse
var n = "null";
n.localeCompare(entry.personalization);
this function returns boolean.
You don't need to wrap null around ''.
Simply use :-
if(entry.personalization == null)

POST max length or JS object max length?

I am stuck with an annoying problem. I have an application on Google App Engine which sends some data (formatted as JSON string) from JS through POST to a php page. But when I select more than a specific amount of data, simply nothing is returned. I already tried to increase post_max_size to 20M, but not better. So where could be a limitation here? Is there another possibility to get data from JS to PHP? I tried like this:
function openWindowWithPost(url, name, keys, values) {
var newWindow = window.open(url, name);
if (!newWindow)
return false;
var html = "";
html += "<html><head></head><body><form id='formid' method='post' action='"
+ url + "'>";
if (keys && values && (keys.length == values.length))
for (var i = 0; i < keys.length; i++)
html += "<input type='hidden' name='" + keys[i] + "' value='"
+ values[i] + "'/>";
html += "</form><script type='text/javascript'>document.getElementById(\"formid\").submit()</sc"
+ "ript></body></html>";
newWindow.document.write(html);
return newWindow;
}
You could possibly check the server configuration file php.ini and check for the maximum post size max_post_size. If the default post string length isn't enough, you could increase it's length.
If you POST those big files, maybe you should check your upload_max_filesize-setting too.
Another possibility: Is your big JSON-File valid? You might try this here:
http://jsonlint.com/
You're likely hitting the 32 MB limit per request. To get around that, you'll need to Upload to GCS instead.

Javascript Error: 'missing ) after argument list"

I am making an image for my webpage through javascript like so:
photoHTMLString = '<li class = "SliderPhoto"><img src = "' + ImageArray[x].src_small + '" size = "thumb" onclick = "ShowImagePopUP(' + ImageArray[x].src_big + ')" class = "FacebookSliderPhoto"/></li>';
Whenever I try and click a photo go into ShowImagePopUP I get this error:
missing ) after argument list
[Break On This Error] ShowImagePopUp(http://a8.sph...389_84095143389_5917147_2636303_n.jpg)
It doesn't look like I am missing any ')'s so I am lost on the error.
Any suggestions?
You need to wrap the contents of ShowImagePopUP in quotes:
"ShowImagePopUp(\'' + ImageArray[x].src_big + '\')"
Which should render as:
ShowImagePopUp('http://a8.sph...389_84095143389_5917147_2636303_n.jpg')
^ note the quote here
Example: http://jsfiddle.net/V23J6/1/
try
photoHTMLString = '<li class = "SliderPhoto"><img src = "'
+ ImageArray[x].src_small
+ '" size = "thumb" onclick = "ShowImagePopUP(\"'
+ ImageArray[x].src_big + '\")" class = "FacebookSliderPhoto"/></li>';
should do the trick and solve your problem leaving intact the uglyness of you code
A function like this one should be a bit readable and ready to use...
function slideElement(image){
var li=document.createElement('li');
var img=document.createElement('img');
li.appendChild(img);
li.setAttribute('class','SliderPhoto');
img.setAttribute('class','FacebookSliderPhoto');
img.setAttribute('size', 'thumb');
img.setAttribute('src', image.src_small);
img.setAttribute('onclick', function(){showImagePopUP(image.src_big);});
return li;
}
The value in ImageArray[x].src_big needs to be quoted.
Try to avoid building HTML by mashing strings together. Using a DOM builder gives code that is much easier to debug.
You'd probably be better off writing this so the function computes the large URI based on the small URI rather than having it hard coded.
Here's some general advice, build up the strings into intermediate variables and then assemble it at the end. You can then use the debugger to find out where you're getting your ' or "s unbalanced. When you have it all built you can coalesce it into a single line if you want or leave it with the intermediate variables.

Categories