phpjsonjsonlint

PHP json_encode() results showing JSONLint errors


I am having issues with validating the output of my json_encode() function.

I am pulling in an XML feed with cURL, converting it into an array, and converting that array into JSON with json_endode(). Ill spare you the cURL stuff:

  foreach ($xmlObjects->articleResult as $articleResult) {
    $article = array(
      "articleResult" =>
      array(
        'articleId' => (string)$articleResult->articleId,
        'title' => (string)$articleResult->title,
        'subhead' => (string)$articleResult->subhead,
        'tweet' => (string)$articleResult->tweet,
        'publishedDate' => (string)$articleResult->publishedDate,
        'image' => (string)$articleResult->image
      ),
    );
    $json = str_replace('\/','/',json_encode($article));
    echo $json;
  }

Which is giving me a JSON readout of:

{
    "articleResult": {
        "articleId": "0001",
        "title": "Some title",
        "subhead": "Some engaging subhead",
        "tweet": "Check out this tweet",
        "publishedDate": "January 1st, 1970",
        "image": "http://www.domain.com/some_image.jpg"
    }
}
{
    "articleResult": {
        "articleId": "0002",
        "title": "Some title",
        "subhead": "Some engaging subhead",
        "tweet": "Check out this tweet",
        "publishedDate": "January 1st, 1970",
        "image": "http://www.domain.com/some_image.jpg"
    }
}

This will give me a JSONLint error saying:

Parse error on line 10:
..._120x80.jpg"    }}{    "articleResult
---------------------^
Expecting 'EOF', '}', ',', ']'

So naturally I will add in the comma, which gives me an End of File expectation:

Parse error on line 10:
..._120x80.jpg"    }},{    "articleResu
---------------------^
Expecting 'EOF'

I am new to JSON, but I have checked the website and a few resources for proper JSON formatting and structure, and from what I can see my readout is following the guidelines. Any pointers?

Resources I've checked:

JSON.org naturally

Wikipedia has well documented page

W3Resource Had a good explanation of structure.

JSONLint


Solution

  • You were encoding 2+ objects into json string, you need [ ] to wrap them

    the correct syntax is

    [ 
       { /* first object */ }
     , { /* second object */ }
     , { /* third object */ }
    ]
    

    the things you need to look out are

    Solution

    $json = array();
    foreach ($xmlObjects->articleResult as $articleResult) {
      $article = array(
        "articleResult" =>
        array(
          'articleId' => (string)$articleResult->articleId,
          'title' => (string)$articleResult->title,
          'subhead' => (string)$articleResult->subhead,
          'tweet' => (string)$articleResult->tweet,
          'publishedDate' => (string)$articleResult->publishedDate,
          'image' => (string)$articleResult->image
        ),
      );
      $json[] = $article;
    }
    echo json_encode($json);