My input JSON string is
{"videos": ["https://www.youtube.com/watch?v=Nt4fp43U2ys", "https://www.youtube.com/watch?v=dU26cGlmkRg", "https://www.youtube.com/watch?v=TxvpctgU_s8"]}
but PHP doesn't seem to parse it properly, since var_dump on $_POST returns
array(1) {\n ["videos"]=>\n string(43) "https://www.youtube.com/watch?v=TxvpctgU_s8"\n}\n`
What am I missing here?
Seems to me the source of the json is outputting newlines "\n". So the parsing is probably not the culprit here, the source is.
Either cleanup the output, or remove the new lines first if you don't control the source.
$decoded = json_decode(trim($jsondata), true);
Related
I made a post in a form converting my javascript localstorage to a post request. From there I tried to decode my json string to make an object in PHP.
How my php code looks before I echo it
$cart_items = $_POST['cart_items'];
$cart_items = json_encode($cart_items);
$array_test = json_decode($cart_items);
print_r($array_test);
What it returns in browser
[{\"id\":83494890,\"title\":\"2020 Hino 358\",\"partType\":\"Bumpers\",\"price\":100,\"stockNumber\":12313131312,\"thumbImg\":\"/jOIY91KhEby8_f.jpg\",\"permalink\":\"/part-description/?part=83494890\",\"maxQuantity\":1,\"requestedQuantity\":\"3\"}
,{\"id\":83493833,\"title\":\"2009 Freightliner 5020080\",\"partType\":\"ABS Modulator Valves\",\"price\":150,\"stockNumber\":\"P-1211111111157\",\"thumbImg\":\"/OOjQbsi6p8kX_f.jpg\",\"permalink\":\"/part-description/?part=83493833\",\"maxQuantity\":1,\"requestedQuantity\":\"1\"}]
I know that typically when seeing json data there isn't forward slashes everywhere. I tried to json_decode into an array rather than an object, then make a foreach for each object inside. But I got this error returned "Invalid argument supplied for foreach()"
How do I make this json string convert to an array of objects? Thank you
The problem I was having was when I was getting the $_POST[] it was using PHP's "magic quotes" which was giving me improper format for my json. That being said, after disabling this, it removes the slashes.
It looks like $_POST['cart_items'] already contains JSON. So you just need to decode it, not encode it first.
$array_test = json_decode($_POST['cart_items'], true);
print_r($array_test);
But it's actually encoded twice, that's why it has escaped quotes, so you need to call json_decode() twice. But it's missing the double quotes around the whole thing, and the embedded newline is not valid.
The following works:
<?php
$cart_items = '"[{\"id\":83494890,\"title\":\"2020 Hino 358\",\"partType\":\"Bumpers\",\"price\":100,\"stockNumber\":12313131312,\"thumbImg\":\"/jOIY91KhEby8_f.jpg\",\"permalink\":\"/part-description/?part=83494890\",\"maxQuantity\":1,\"requestedQuantity\":\"3\"},{\"id\":83493833,\"title\":\"2009 Freightliner 5020080\",\"partType\":\"ABS Modulator Valves\",\"price\":150,\"stockNumber\":\"P-1211111111157\",\"thumbImg\":\"/OOjQbsi6p8kX_f.jpg\",\"permalink\":\"/part-description/?part=83493833\",\"maxQuantity\":1,\"requestedQuantity\":\"1\"}]"';
$array_test = json_decode(json_decode($cart_items));
print_r($array_test);
I suggest you find the code that's sending the cart_item POST parameter and fix it so it doesn't do all this extra encoding.
I need to use a customer's API for loading JSON which only contains something like:
{"html" : "foo"}
The API is being used from other services so I'm pretty sure it's valid.
However, when trying to decode it using json_decode i'm always getting an empty string which means it's not valid. I found out i need to "fix" the JSON-String by replacing:
$json = str_replace("\\>", "\\\\>", $json); // \> = invalid json
It works mainly on each request but not on certain others but it's very tricky to debug and i can't imagine that replacing is the proper method.
How would i do it the easy way for converting the json string into a valid one?
thanks
Ok i could find out what's wrong:
The HTML contains backslashes in the closing tags, for example <br\>
You need to replace them like this:
$json = str_replace("\\>", "\\\\>", $json);
and json_decode will work
I'm building an API in php. This API processes json messages from a third party API.
I want to log invalid pretty printed json messages.
So I did this:
error_log("test\n" . json_encode($json_string, JSON_PRETTY_PRINT));
However, when I look at my logs, the json string is not pretty printed:
$ tailf error.log
2015-07-13 10:20:03: (mod_fastcgi.c.2701) FastCGI-stderr: test
"{\"info\":{\"status\":200,\"msg\":\"OK\"},\"response\":{\"foo\":\"bar\"}"
I want to see something like:
$ tailf error.log
2015-07-13 10:20:03: (mod_fastcgi.c.2701) FastCGI-stderr: test
{
"info": {
"status": 200,
"msg ": "OK"
},
"response": {
"foo": "bar"
}
}
How can I achive this result?
error_log("test\n" . json_encode($json_string, JSON_PRETTY_PRINT));
json_encode() will actually not necessarily produce JSON: it will produce something that can be read by javascript. If you give it an array or an object, it will produce JSON; if you give it a string, it will produce a javascript string. And that’s what you’re doing, so that’s what you’re getting.
To be clear, $json_string is a string: (as far as PHP is concerned, it’s a string; if you passed that same string to javascript, it would be interpreted as an object). You pass that through json_encode() and all you’re going to get is another string (a string of doubly-encoded JSON).
JSON_PRETTY_PRINT is having no effect here, because you’re not producing JSON: you’re producing something that javascript too would see as a string.
Savvy?
So what you need to do is to (a) turn $json_string back into a PHP array, and then (b) reencode that as JSON, this time using the JSON_PRETTY_PRINT flag.
$log_array = json_decode($json_string, true);
$json_pretty_string = json_encode($log_array, JSON_PRETTY_PRINT);
error_log('test' . PHP_EOL . $json_pretty_string);
Rather than converting it back to a PHP array and then back to JSON, it would be better to add the JSON_PRETTY_PRINT flag to wherever you’re getting $json_string from in the first place, if possible.
Alternatively, just log $json_string directly (no need to encode it: it’s already a string, you can pass it to error_log() as it is), and worry about prettifying it only when you need to read your logs. This will make your logs considerably smaller.
Common unix error logs are not supposed to contain human-readable json or other unescaped characters. Many syslog/logging implementations are limited by character width and automatically add encoding (like \") or remove new line characters, PHP's error_log is not binary safe either - the behaviour when encountering a unicode character is unpredictable tho (not sure).
You should not be using the native syslog/error log functions, instead,
build your own logger, dedicated to json logging.
Personally I use MongoDB for logging json, because it's the kind of data MongoDB is supposed to work with.
You have two options in this case,
if you can use a str_replace like:
error_log("test\n" . str_replace('\"',"\n",json_encode($json_string, JSON_PRETTY_PRINT)));
or like #Karoly Horvath said:
You encode a string already encoded in a JSON. Your $json_string is already encoded. So you need to decode your first JSON and re-encode it with good parameters
error_log("test\n" . json_encode(json_decode($json_string), JSON_PRETTY_PRINT));
and give credit to #Karoly.
I have a strange JSON decoding problem in PHP. A certain JSON file (and only this) produces reliably a decoding error. The PHP part is nothing special:
$data = array();
if (is_file(DIR.'config.json')) {
$data = json_decode(DIR.'config.json');
}
// diagnostics:
var_dump($data); // --> NULL (would be array() if decoding didn't happen)
var_dump(json_last_error()); // --> int(4) === JSON_ERROR_SYNTAX
var_dump(json_last_error_msg()); // --> string(20) "unexpected character"
echo file_get_contents(DIR.'config.json'); // --> '["a"]'
What I've tried:
Simplify JSON. The content of the file now is ["a"].
validate JSON, just to be sure, in four validators, including jsonlint.com and pasting it in browser console
No BOM, plain ASCII file
has read rights. The above echo works just fine.
completely independent of JSON file's content.
path is correct. Proven by above echo statement. JSON file is in the docroot.
Unfortunately PHP's JSON lib doesn't state errors more precisely, so I have no idea, what really causes the error.
Has anyone an idea, how I could proceed?
You're not decoding the file contents, but rather the name of the file itself, which is why you're getting null. Your code should be:
$data = array();
if (is_file(DIR.'config.json')) {
$data = json_decode(file_get_contents(DIR.'config.json'));
}
json_decode(DIR.'config.json');
You are trying to decode the string "<whatever-DIR-is>config.json". That's not a valid JSON string. You probably want:
json_decode(file_get_contents(DIR.'config.json'));
You also probably want more coffee.
I'm trying to encode a response array as json and it has worked until now.
$response = array();
$response['icons']= $icons_arr;
$response['message']= $msg;
echo json_encode( $response );
The result is
Array{"icons":["{\r\n\t\t\t\t\t\"icon_web_id\": \t\t\t\"0 ...
Javascript throws an error as it can't parse the "Array" word. I suspect the JQuery function $.parseJSON() expects a {} or a [].
What am I doing wrong here? Why won't json_encode() function properly?
Bonus question: what is causing all these \t\t\t\t's to occur?
Some other piece of code is producing the 'Array' output before the json string is output, you can prove this by changing the output line to
echo "json_encode returned ".json_encode( $response );
Check your code for other echo statements.
Regarding your Bonus question:
The \t is a tab in PHP. Your code may contain tabs instead of spaces somewhere, which could be rendered as multiple \t's.