Young-Ho Kim
Young-Ho Kim

Reputation: 193

Decoding multiline string in JSON file using json_decode()

I'm new to JSON so having some trouble parsing it.

I made a JSON file:

newjson.json

{
    "title":"My Title",
    "contents":"My\
                Multiline\
                Contents"
}

I used \ to avoid an error in JavaScript syntax that doesn't allow multiline strings, but when I load it with file_get_contents() and decode it using json_decode() in PHP, it can't parse it.

I think I should handle the \s with preg_replace, or something before I put the string in a decode function.

What should I do?

Upvotes: 0

Views: 4370

Answers (2)

sandeepKumar
sandeepKumar

Reputation: 811

there must be something wrong in your in json syntax that's why it can't parse it...

try your http://json.parser.online.fr/

copy your whole json string there and try to manipulate that...you may find your error there

Upvotes: 1

Ry-
Ry-

Reputation: 224942

PHP can't parse your string because it's not valid JSON. The only valid escape sequences are:

  • \" for a quotation mark
  • \\ for a backslash
  • \/ for a forward slash
  • \b for a backspace
  • \f for a formfeed
  • \n for a newline
  • \r for a carriage return
  • \t for a tab
  • \uxxxx for a hexadecimal escape

Use a newline escape instead if you want literal newlines. Otherwise, you'll have to live with a less-pretty string.

{
    "title":"My Title",
    "contents":"My\nMultiline\nContents"
}

Upvotes: 5

Related Questions