[Geojson] JSON.parse: unexpected character

Michael Geary mg at mg.to
Wed Jul 11 09:43:29 PDT 2012


The JSON.parse() error means just what it says: there is an unexpected
characer in your JSON data.

You didn't show us the JSON data itself, but the screenshot has enough of a
clue about what went wrong.

Look at the call frame at the top of the stack: your nativeJSON() function.
The variable named 'a' contains your JSON data, yes?

Look at that JSON string. It starts with several newlines (Windows-style
newlines with \r\n), followed by:

    <--det...

That is the beginning of an HTML comment. It is not JSON.

Why is that in your JSON data? Look at your PHP file. It begins with a
<?php section, but then it *ends* that section with ?> followed by this
HTML comment:

    <!--determinar inicio e fim da rota-->

There is your bad JSON data.

The fix is easy. Here is what you should do whenever you write a PHP file
that generates JSON or any other non-HTML format:

1) Make sure the very first line of the file is <?php as you already have.

2) Do not end the PHP code with ?> anywhere. Don't even use ?> at the end
of the file! Yes, that's right, don't use it at the end of the file. It is
not required, and using it at the end of the file is likely to add an
unnecessary newline because in most editors you'll probably have a newline
after the ?>.

Those two rules insure that your entire PHP file is pure PHP code and does
not have any spurious HTML code or HTML comments sneaking into your output
data.

Of course, you will also now need to change your HTML comments to PHP //
comments.

That should fix the JSON parsing error. At least it will insure that what
the PHP code outputs is what you expect it to output.

-Mike

On Wed, Jul 11, 2012 at 4:53 AM, Pedro Costa <pedrocostaarma at sapo.pt> wrote:

> Hello,
>
> This is my first mail to this list.
>
> I have a php script that have to return to client a geojson layer but it
> gives me this error in firebug:
>
> JSON.parse: unexpected character (screen shot attached)
>
>
> the php code is that:
>
> http://pastebin.com/tSCv5cnT
>
>
> Can somebody help me with the error?
>
> thanks
>
>
>
>
>
> _______________________________________________
> Geojson mailing list
> Geojson at lists.geojson.org
> http://lists.geojson.org/listinfo.cgi/geojson-geojson.org
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.geojson.org/pipermail/geojson-geojson.org/attachments/20120711/1a05d159/attachment.htm>


More information about the GeoJSON mailing list