Sonelal
Sonelal

Reputation: 11

How to convert string that contains multiple json data in proper json format in php?

How can I convert this string:

{"id":"tag:search.twitter.com,2005:1"}{"id":"tag:search.twitter.com,2005:2"}
{"id":"tag:search.twitter.com,2005:3"}{"id":"tag:search.twitter.com,2005:4"}

Into this JSON format:

[
    {"id":"tag:search.twitter.com,2005:1"},
    {"id":"tag:search.twitter.com,2005:2"},
    {"id":"tag:search.twitter.com,2005:3"},
    {"id":"tag:search.twitter.com,2005:4"}
]

Upvotes: 0

Views: 717

Answers (3)

Sonelal
Sonelal

Reputation: 11

Thanks for giving your comments on my question...I have resolved my issue by putting below code

    foreach (preg_split("/((\r?\n)|(\r\n?))/", $tdata) as $line)
    {
    print_r(json_decode($line));      
    }

Upvotes: 1

Elwinar
Elwinar

Reputation: 9509

Assuming that your string is composed of valid JSON object put together without any delimiter, you can do the following:

  1. Split the string with }{ as delimiter
  2. Loop over each item in the resulting array and add the missing parts
  3. Merge the array into one string with a , as delimiter
  4. Add the JSON array marks before and after the string

Example (with $input as the input string):

$chunks = explode('}{', $input);
$n = count($chunks);
for($i = 0; $i < $n; $i++) {
    if($i == 0) {
        $chunks[$i] = $chunks[$i].'}';
    } else if($i == $n - 1) {
        $chunks[$i] = '{'.$chunks[$i];
    } else {
        $chunks[$i] = '{'.$chunks[$i].'}';
    }
}
$output = '['.implode(',', $chunks).']';

Note that it will work on imbricated structures, but will miserably fail if you have a }{ in the text. But it is unlikely.

EDIT: One simple way of checking if the current chunk is a wrong cut could be by checking is the next chunk start with a ", because JSON object's attributes are always quoted. If not, then you can merge the current and next chunk and repeat until finding the right character.

Upvotes: 0

Sven van Zoelen
Sven van Zoelen

Reputation: 7219

You can do it like this:

$str = '{"id":"tag:search.twitter.com,2005:1"}{"id":"tag:search.twitter.com,2005:2"}
{"id":"tag:search.twitter.com,2005:3"}{"id":"tag:search.twitter.com,2005:4"}';

// wrap the string in [] to make it an array (when decoded).
// replace all the '}<spaces/line breaks/tabs>{' to '},{' to make it valid JSON array.
// decode the new JSON string to an object.    
$obj = json_decode('[' . preg_replace('/}\s*{/', '},{', $str) . ']');

var_dump($obj);

Output:

array (size=4)
  0 => 
    object(stdClass)[424]
      public 'id' => string 'tag:search.twitter.com,2005:1' (length=29)
  1 => 
    object(stdClass)[517]
      public 'id' => string 'tag:search.twitter.com,2005:2' (length=29)
  2 => 
    object(stdClass)[518]
      public 'id' => string 'tag:search.twitter.com,2005:3' (length=29)
  3 => 
    object(stdClass)[519]
      public 'id' => string 'tag:search.twitter.com,2005:4' (length=29)

Upvotes: 1

Related Questions