NotionCommotion Posted December 31, 2016 Share Posted December 31, 2016 Am I doing this correctly? Thanks <?php function parse($s) { static $buffer; $jsons=[]; $arr=[]; $parts=explode('\n',$s); $count=count($parts); if($count===1) { $buffer.=$parts[0]; } elseif($count===2) { if($start=$buffer.$parts[0]) $jsons[]=$start; $buffer=$parts[1]; } else { if($start=$buffer.$parts[0]) $jsons[]=$start; if($count>3) { $jsons=array_merge($jsons,array_slice($parts,1,$count-2)); } $buffer=$parts[$count-1]; } foreach($jsons as $json) { $arr[]=json_decode($json); } return $arr; } var_dump(parse('{"a":123,"b":[1,2')); var_dump(parse('')); var_dump(parse(',3]}\n{"a":321,"b":[3,2,1]}\n{"a":111,"b":[1,1,1]}\n{"a":333,"b":[3,3,3]}\n{"a":123,"b":[1,2,3]}\n{"a"')); var_dump(parse(':321,"b":[3,2,1]}\n{"a":111,"b":[1,1,1]}\n{"a":333,"b":[3,3,3]}\n')); var_dump(parse('{"a":333,"b":[3,3,3]}\n')); array(0) { } array(0) { } array(5) { [0]=> object(stdClass)#1 (2) { ["a"]=> int(123) ["b"]=> array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } } [1]=> object(stdClass)#2 (2) { ["a"]=> int(321) ["b"]=> array(3) { [0]=> int(3) [1]=> int(2) [2]=> int(1) } } [2]=> object(stdClass)#3 (2) { ["a"]=> int(111) ["b"]=> array(3) { [0]=> int(1) [1]=> int(1) [2]=> int(1) } } [3]=> object(stdClass)#4 (2) { ["a"]=> int(333) ["b"]=> array(3) { [0]=> int(3) [1]=> int(3) [2]=> int(3) } } [4]=> object(stdClass)#5 (2) { ["a"]=> int(123) ["b"]=> array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } } } array(3) { [0]=> object(stdClass)#5 (2) { ["a"]=> int(321) ["b"]=> array(3) { [0]=> int(3) [1]=> int(2) [2]=> int(1) } } [1]=> object(stdClass)#4 (2) { ["a"]=> int(111) ["b"]=> array(3) { [0]=> int(1) [1]=> int(1) [2]=> int(1) } } [2]=> object(stdClass)#3 (2) { ["a"]=> int(333) ["b"]=> array(3) { [0]=> int(3) [1]=> int(3) [2]=> int(3) } } } array(1) { [0]=> object(stdClass)#3 (2) { ["a"]=> int(333) ["b"]=> array(3) { [0]=> int(3) [1]=> int(3) [2]=> int(3) } } } Quote Link to comment https://forums.phpfreaks.com/topic/302843-parsing-newline-delimited-json/ Share on other sites More sharing options...
bsmither Posted January 1, 2017 Share Posted January 1, 2017 (edited) If you are concerned about getting an array of objects instead of an array of associative arrays, use: json_decode($json, true) Realize you will end up with null elements in the output objects if parsing a string having three or more delimiters where any two or more are consecutive. Edited January 1, 2017 by bsmither Quote Link to comment https://forums.phpfreaks.com/topic/302843-parsing-newline-delimited-json/#findComment-1540922 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.