I want to parse some json response into php array, the problem is nginx push stream module response with not separated json string, is possible to parse this without using regex?
'{"id":1,"channel":"1","text":"Hello World!"}{"id":2,"channel":"1","text":"Hello World!"}{"id":2,"channel":"1","text":{"key_x": "value_x"}}'
Edit
The real issue was that nginx push-stream module send archive in stream, so thats why there is no separator between json data in my snippet.
$str = '{"id":1,"channel":"1","text":"Hello World!"}{"id":2,"channel":"1","text":"Hello World!"}{"id":2,"channel":"1","text":"Hello World!"}';
$str = str_replace('}{', '},{', $str);
$str = '[' . $str . ']';
print_r(json_decode($str));
https://3v4l.org/BNVTg
I dont think this is actually possible without either changing the output or use regex / str_replace.
If you have control over the output you should change the output to valid json:
{"data":[
{"id":1,"channel":"1","text":"Hello World!"},
{"id":2,"channel":"1","text":"Hello World!"},
{"id":2,"channel":"1","text":"Hello World!"}
]}
It you cant do this then you could try to use str_replace with explode:
$data = str_replace('}{', '}<should_be_absolut_unique>{');
foreach( explode('<should_be_absolut_unique>', $data) as $json ){
# json_decode($json)
}
This is of course very unsave and not guaranteed to work because you dont know if the string replace works correctly if you do not know the data that is send!
Related
I working at PHP Project With PHP Version 7.0.13
I was dealing with JSON lately, I have a JSON file that needs to be decode to PHP but before I decode the JSON, I need to clean some abstract string inside the file that JSON obtained inside, to clean the string using substr() to get the JSON.
when i write the code, like this:
$jsonraw = "\"{ JSON should be here, later }\"";
$cutstart = strpos($jsonraw, "{");
$cutend = strrpos($jsonraw, "\"");
$jsonclean = substr($jsonraw, $cutstart, $cutend);
echo $jsonclean;
The output is like this
{ JSON should be here, later }
But when the string is like this
$jsonraw = "\"some abstract string to remove { JSON should be here, later }\"";
The output is became like this
{ JSON should be here, later }"
As we can see there was a quote symbol " at the last of the string, I was trying to decrement the $cutend, like this $jsonclean = substr($jsonraw, $cutstart, --$cutend); and this to $cutend-1
Any help, I appreciate.
Sorry for my bad English
You can use preg_match to get the json from that string:
$string = "some abstract string to remove { JSON should be here, later }";
preg_match('/\{.*\}/', $string, $match);
var_dump($match[0]);
the result would be:
string(30) "{ JSON should be here, later }"
As the third parameter is the length of the string, you need to say that the length is the end position minus the start position...
$jsonclean = substr($jsonraw, $cutstart, $cutend-$cutstart);
I currently have this code running. It is splitting the variable $json where there are },{ but it also removes these characters, but really I need the trailing and leading brackets for the json_decode function to work. I have created a work around, but was wondering if there is a more elegant solution?
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5},{"a":1,"b":2,"c":3,"d":4,"e":5}';
$individuals = preg_split('/},{/',$json);
$loop_count =1;
foreach($individuals as $object){
if($loop_count == 1){$object .='}';}
else{$object ="{".$object;}
print_r(json_decode($object));
echo '<br />';
$loop_count++;
}
?>
EDIT:
The $json variable is actually retrieved as a json object. An proper example would be
[{"id":"foo","row":1,"col":1,"height":4,"width":5},{"id":"bar","row":2,"col":3,"height":4,"width":5}]
As you (presumably) already know, the string you have to start with isn't valid json because of the comma and the two objects; it's basically two json strings with a comma between them.
You're trying to solve this by splitting them, but there's a much easier way to fix this:
The work-around is simply to turn the string into valid JSON by wrapping it in square brackets:
$json = '[' . $json . ']';
Voila. The string is now valid json, and will be parsed successfully with a single call to json_decode().
Hope that helps.
You can always add them again.
Try this:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5},{"a":1,"b":2,"c":3,"d":4,"e":5}';
$individuals = preg_split('/},{/',$json);
foreach($individuals as $key=>$val)
$individuals[$key] = '{'.$val.'}';
I'm sending comma separated values through a URL (key, value). I'm encoding them with Javascript's escape() and then replacing the commas within each value with %2c . The problem is at the PHP end the commas that are encoded are turned into "," BEFORE explode() takes place and then my string containing commas is broken up and it doesn't save right.
How can I stop PHP from converting my encoded bits back into unencoded bits?
My JS for each input is:
fieldData += $(this).attr("id")+","+escape($(this).html()).replace(/,/g,"%2c")+",";
My PHP is:
$fieldData = explode(",", $_POST['fieldData']);
Tried (along with other things):
$fieldData = explode(",", urlencode($_POST['fieldData']));
I would suggest using base64encode/decode for this.
The javascript would look something like this: http://jsfiddle.net/Y6yuN/
<script src='http://javascriptbase64.googlecode.com/svn/trunk/base64.js'></script>
fieldData += $(this).attr("id")+","+escape(Base64.encode($(this).html()))+",";
The escape is for the trailing =
So you would end up with comma delimited base64 encoded strings.
On the PHP side:
$fieldData = explode(",", $_POST['fieldData']);
foreach ($fieldData as $k => $v){
$fieldData[$k] = base64_decode(urldecode($v));
}
Your post is not really well explained, but I think you want to decode the data passed by JS. So, the code should be:
$fieldData = explode(",", urldecode($_POST['fieldData']));
Try to write it better if I am wrong!
I have a variable which contains a path in json_encode
/users/crazy_bash/online/test/
but json_encode converts the path to this:
\/users\/crazy_bash\/online\/test\/
Why? How can i display a normal path?
the code
$pl2 = json_encode(array(
'comment' => $nmp3,
'file' => $pmp3
));
echo($pl2);
It's perfectly legal JSON, see http://json.org/. \/ is converted to / when unserializing the string. Why worry about it if the output is unserialized by a proper JSON parser?
If you insist on having \/ in your output, you can use str_replace():
// $data contains: {"url":"http:\/\/example.com\/"}
$data = str_replace("\\/", "/", $data);
echo $data; // {"url":"http://example.com/"}
Note that it's still valid JSON by the definition of a string:
(source: json.org)
Escaped solidus is legal. But if you want a result without escaping, use JSON_UNESCAPED_SLASHESin json_encode option. However, this was added after PHP 5.4.
So, str_replace('\\/', '/', $pl2); would be helpful.
You'll have to decode it before usage.
json_decode()
That's what json_encode is supposed to do. Once you json_decode or JSON.parse it, it's fine.
var f = {"a":"\/users\/crazy_bash\/online\/test\/"}
console.log(f.a); // "/users/crazy_bash/online/test/"
var h = JSON.parse('{"a":"\/users\/crazy_bash\/online\/test\/"}');
console.log(h.a); // "/users/crazy_bash/online/test/"
I had the same problem, basically you need to decode your data and then do the encode, so it works correctly without bars, check the code.
$getData = json_decode($getTable);
$json = json_encode($getData);
header('Content-Type: application/json');
print $json;
I need to grab a json-string from this page: https://retracted.com
If you view the source, I json-string starts after var mycarousel_itemList =. I need to parse this string as a correct json-array in my php-script.
How can this be done?
EDIT: I've managed to pull this off using explode, but the method is ugly as heck. Is there no build-in function to translate this json-string to a array?
To clarify: I want the string I grab (which is correct json) to be converted into a php-array.
The JSON in the script block is invalid and needs to be massaged a bit before it can be used in PHP's native json_decode function. Assuming you have already extracted the JSON string from the markup (make sure you exclude the semicolon at the end):
$json = <<< JSON
[ { address: 'Arnegårdsveien 32', … } ]
JSON;
var_dump(
json_decode(
str_replace(
array(
'address:',
'thumb:',
'description:',
'price:',
'id:',
'size:',
'url:',
'\''
),
array(
'"address":',
'"thumb":',
'"description":',
'"price":',
'"id":',
'"size":',
'"url":',
'"'
),
$json
)
,
true
)
);
This will then give an array of arrays of the JSON data (demo).
In other words, the properties have to be double quoted and the values need to be in double quotes as well. If you want an array of stdClass objects instead for the "{}" parts, remove the true.
You can do this either with str_replace as shown above or with a regular expression:
preg_match('
(.+var mycarousel_itemList = ([\[].+);.+function?)smU',
file_get_contents('http://bolig…'),
$match
);
$json = preg_replace(
array('( ([a-z]+)\:)sm', '((\'))'),
array('"$1":', '"'),
$match[1]
);
var_dump(json_decode($json, true));
The above code will fetch the URL, extract the JSON, fix it and convert to PHP (demo).
Once you have your json data, you can use json_decode (PHP >= 5.2) to convert it into a PHP object or array