json_encode and JSON.parse does not harmonize - javascript

I get this output on my php page with json_encode
{"id":"761","user":"Moderator","message":"test"}
{"id":"760","user":"Patrick","message":"test"}
Now i want to parse theses values with JSON.parse in javascript, to get an array.
But it does not work.
It works only if i have one json Objekt.
What is the best way to solve this?
To split at '}' and parse every string that i will get?

{}{} is not valid JSON. You need to have an array wrap these and separate them with commas like [{},{}]. You can do this in PHP via:
$entries = array();
foreach ($database_entry as $array) {
$entries[] = $array;
}
echo json_encode($entries);
That is you should only call json_encode once.

This output is not a proper JSON object or array. What you want to do is wrap your objects in square brackets, and separate them with commas. The output should look like this:
[{"id":"761","user":"Moderator","message":"test"},
{"id":"760","user":"Patrick","message":"test"}]
You will need to change your PHP to generate the output in this way.

JSON.parse applies only strings:
JSON.parse(text[, reviver])
text is
the string to parse as JSON. See the JSON object for a description of JSON syntax. MDN.

You'll need to output the objects into a JSON array, with each object/array item separated by a comma:
{
"users": [
{"id":"761","user":"Moderator","message":"test"},
{"id":"760","user":"Patrick","message":"test"}
]
}

Related

parse a string that contains array with strings

I am struggling to parse a string that contains array. And the array also contains list of arrays.
Each of the array contains string.
code here
let a = "[[48934, 'Danial Brendon', 'developer'],[48934, 'Nicki Lopez', 'developer']]";
console.log(JSON.parse(a))
I tried using JSON.parse() but did not work, may be because JSON.parse() also want to parse the string.
I am having difficulty with this even this looks simple. I could not find any similar question/answer like this.
Thanks.
To JSON parse , you need double quotes instead of single. like this ...
let a = '[[48934, "Danial Brendon", "developer"],[48934, "Nicki Lopez", "developer"]]';
console.log(JSON.parse(a));

How to convert JSON Parse object property into array?

In mysql database, "diagID" is saved as json_encoded(array). Now i need it to retrieve in ajax success.
How to convert JSON parse data into array, as it's showing string?
var ajaxResponse= {
"id": "123",
"diagID" : "['101','125','150','230']"
}
typeof(ajaxResponse.diagID)
= string
In javascript typeof(ajaxResponse.diagID) shows string. How to convert it into array?
Decoding it in php would make most sense
$diagID = json_decode($diagID, true);
Then when you json_encode() the whole response it won't have the extra wrapping quotes.
Note however that the strings in array have single quotes which are not valid json and need to be replaced with double quotes before they can be parsed in either language

Using json_encode on php $_GET array results in string rather than array of strings

I'm trying to use the php GET method to create an array of keywords from a keywordBox field on another page.
Here is an example of the keywords appended to the page URL:
/searchResults.php?keywordBox=computing+finance
This looks okay to me but when I convert to a JSON object it seems the keywords become a single string ("computing finance") rather than array of strings (["computing", "finance"])
var keywords = <?php echo json_encode($_GET['keywordBox']) ?>;
alert(keywords[0]); // output "c"
I thought this would output the first word in the array "computing" instead it outputs the first character "c" so I'm a little confused and new to these languages. Any explanation greatly appreciated.
keywordBox can be an array, just change your query string with:
?keywordBox[]=computing&keywordBox[]=finance
Otherwise you can keep it as a string, and explode it.
var keywords = <?php echo json_encode(explode(' ', $_GET['keywordBox'])) ?>;
Pay attention to what you're encoding.
This only encodes one GET parameter, not the $_GET superglobal array:
var keywords = <?php echo json_encode($_GET['keywordBox']) ?>;
With your given URL and the parameter keywordBox=computing+finance, $_GET['keywordBox'] will contain a single string, "computing finance", not an array. If you want the parameter to contain an array, you need to use array notation, as in keywordBox[]=computing&keywordBox[]=finance.

Why am I getting an error message about "unexpected non-whitespace after JSON data"

Can anybody tell me what the problem is with this:
I am echoing out a PHP array into javascript as follows:
<?php
$myArray=array();
foreach ($persons as $person) {
array_push($myArray,$person['id']);
}
?>
$(document).ready(function() {
populatePersons(JSON.parse(<?php echo json_encode($myArray);?>));
});
So basically I am echo'ing out a PHP array in json format, and then parsing it in javascript but I am getting this error in my console log:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
Can anybody tell me what I am doing wrong?
Can anybody tell me what I am doing wrong?
While json_encode produces JSON, you are echoing it into JavaScript. As such it will be interpreted as a JavaScript array literal, not a string containing JSON. Hence you cannot use JSON.parse.
Just get rid of it:
populatePersons(<?php echo json_encode($myArray);?>);
If you looked at the generated code, you would something like:
populatePersons(JSON.parse([1,2,3]));
But JSON.parse expects a string (containing JSON). Because JavaScript performs type conversion, it will convert the array to a string first, which likely does not result in valid JSON.
Again: You already have an array, there is no need to parse anything.
Its because youre feeding JSON.parse an array. Just get rid of the JSON.prase in your javascript and replace it with JSON.stringify if youre trying to display the json. If not, then json_encode($myArray) should be enough for operations.
<div id = 'test'></div>
<script>
var test = document.getElementById('test');
test.innerHTML = JSON.stringify(<?php echo json_encode($myArray)?>);
</script>
Try putting the json_encode string in quotes.
populatePersons(JSON.parse('<?php echo json_encode($myArray);?>'));
As the parameter expected is string.

get JSONS from a single string

i get a single String value as
"{"Link":"","DefaultValue":"","Content":"LONDON"}, {"Link":"","DefaultValue":"","Content":"United Kingdom"}"
which contains two jsons . how can i get each json and put in into an array or something in javascript/jquery ?
Please suggest the best way.
The String that you posted isn't valid JSON format. If it is an array of two objects, it should read:
'[{"Link":"","DefaultValue":"","Content":"LONDON"}, {"Link":"","DefaultValue":"","Content":"United Kingdom"}]'
Note the single quotes at the beginning and end, so that Javascript doesn't confuse the double quotes in the JSON and can parse them correctly.
Also note the brackets [] around the whole thing, that tells the parser that it is an array of objects.
You can read the new string into an object array like this:
var str = '[{"Link":"","DefaultValue":"","Content":"LONDON"}, {"Link":"","DefaultValue":"","Content":"United Kingdom"}]';
var arr = JSON.parse(str);

Categories

Resources