0

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?

2 Answers 2

5

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"
}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, I just wanted to seperate long string contents for readability when writing it. Then isn't that possible? should I have to let it in one line?
@Young-HoKim: Yes, it will have to be in one line.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.