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);
Related
I receive data like this:
$string = "\x01\x03\r\x08\xc0";
From this variable how to output (with echo) the same value?
For example on python, when I type:
$ print [string]
I get this
["\x01\x03\r\x08\xc0"]
Note:
Without do $string = '\x01\x03\r\x08\xc0' because I uses a server who receives data and the string variable is the data.
Can someone can help me?
when php interpreter reach the line:
$string = "\x01\x03\r\x08\xc0";
it automatically parse string between double quotes. so you can not get real string. but if you can guarantee that response you get is a valid hex, use function bin2hex(). in that case you can convert result of that function to what you want. something like:
$str = bin2hex($hex);
$real_str = '';
for($i=0; $i<strlen($str); $i+=2){
$real_str .= '\\x'.$str[$i].$str[$i+1];
}
echo $real_str;
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!
I have a huge string dump that contains a mix of regular text and JSON. I want to seperate/remove the JSON objects from the string dump and get the text only.
Here is an example:
This is some text {'JSON':'Object'} Here's some more text {'JSON':'Object'} Yet more text {'JSON':'Object'} Again, some text.
My goal is to get a text dump that looks like this (basically the JSON is removed):
This is some text Here's some more text Yet more text Again, some text.
I need to do this all in PHP. The text dump is always random, and so is the JSON data structure (most of the it is deeply nested). The dump may or may not start with JSON, and it may or may not contain more than one JSON object within the string dump.
I have tried using json_decode on the string but the result ends up as NULL
EDIT: Amal's answer is really close to what I want (see the 2nd comment below):
$str = preg_replace('#\{.*?\}#s', '', $str);
However, it doesn't get rid of nested objects at all; e.g. data contained in brackets: [] or [{}]
Sorry, I'm not an expert in regex.
I realized that some of you may need a more concrete example of the string dump I'm dealing with; therefore I've created a gist (please note that this is not static data; the data in the dump will always be different; my example above just simplifies the string I'm working with): https://gist.github.com/anonymous/6855800
I wanted you to post the code you used in your attempt using JSON_decode but oh well...
You can use a recursive regex for nested braces in PHP:
$res = preg_replace('~\{(?:[^{}]|(?R))*\}~', '', $text);
regex101 demo (The part highlighted in blue will be removed).
take a stack and start iterating over the string from the begining.
for($i=0;i<count($str);$i++){
}
whenver you find $str[i] == '{' push this element into the stack and initialize the start variable to $i:
$start = $i;
now whenver a { or [ occurs in th string start push into the stack.
if ] or } occurs and the top of the stack is not { or ] that means this is not a correct json.
if not so then pop the top of stack and keep on doing so until stack is empty.
at that point you get $end = $i;
this will be one of the json string. (from $start to $end)
push this string into another array which keeps all the jsons.
and keep on processing till you reach the end
Here is a working code snippet that works based on animesh seth's answer.
if (strpos($msg, '{') !== false) {
$msg = str_split($msg);
// extract the json message.
$json = '';
$in = 0;
foreach ($msg as $i => $char) {
if ($char == '{') {
$in++;
}
if ($in) {
$json .= $msg[$i];
}
if ($char == '}') {
$in--;
}
}
if ($json) {
$json = json_decode($json);
}
// do something with the json object.
}
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.'}';
Does anyone know why this happens?
var_dump(json_decode(stripslashes(json_encode(array("O'Reiley"))))); // array(1) { [0]=> string(8) "O'Reiley" }
var_dump(json_decode(stripslashes(json_encode(array("O\'Reiley"))))); // NULL
Are ' used at all by the JSON functions?
I don't know for sure, but json_last_error() should :)
My guess, though, is that json_encode() does something to the \' that the stripslashes() then breaks - e.g. add another "\" to escape the backslash.
Isn't fiddling with a json encoded string using striplslashes() before it's decoded wrong anyway?
I didn't look at it too deeply, but it looks like your code is
Taking a PHP Array and turning it into a json string
Mucking with that string
Trying to decode the mucked string as json
Think of it like this
$json_string = json_encode(array("O\'Reiley");
$json_string = stripslashes($json_string);
//it's no longer json, its just some random non-conforming string
var_dump(json_decode($json_string))
You should try without stripslashes()
$result = json_encode(striptslashes(array("O\'Reiley")));
if(json_last_error() > 0){
$result = json_encode(array("O\'Reiley"));
}