user906153
user906153

Reputation: 1218

Why are there invalid characters in this JSON?

My JSON looks something like this:

{
  "Master" : {
    "Major" : "S",
    "Minor" : "E",
    "IPAddress" : "0.0.0.0",
    "Detail":"<root>
               <key keyname=\"state\">3</key>   
               <key keyname=\"oldState\">1</key>        
               <key keyname=\"currency\"></key>
               <key keyname=\"denomination\"></key></root>",    
    "SourceCreateDate" : "2014-04-03T14:02:57.182+0200"
   },
   "Messages" : [{
    "MessageCode" : "0",                    
    "MessageType" : "8"
   }]
}

I'm getting an 'Invalid Characters found' error when validating this. Where are the invalid characters and how can I make this JSON valid?

Upvotes: 4

Views: 7885

Answers (4)

Marchah
Marchah

Reputation: 158

{
"Master": {
    "Major": "S",
    "Minor": "E",
    "IPAddress": "0.0.0.0",
    "Detail": "<root><key keyname=\"state\">3</key><key keyname=\"oldState">1</key><key keyname=\"currency\"></key><key keyname=\"denomination\"></key></root>",
    "SourceCreateDate": "2014-04-03T14:02:57.182+0200"
},
"Messages": [
    {
        "MessageCode": "0",
        "MessageType": "8"
    }
]
}

JSON validator: http://jsonlint.com/

Edit: Explication: when you open a " you need to close it on the same line. So you have to put your xml on a single line or to escape it.

Upvotes: 7

kumar
kumar

Reputation: 770

try this,

{
    "Master": {
        "Major": "S",
        "Minor": "E",
        "IPAddress": "0.0.0.0",
        "Detail": "<root><key keyname=\"state\">3</key><key keyname=\"oldState\">1</key><key keyname=\"currency\"></key><key keyname=\"denomination\"></key></root>",
        "SourceCreateDate": "2014-04-03T14:02:57.182+0200"
    },
    "Messages": [
        {
            "MessageCode": "0",
            "MessageType": "8"
        }
    ]
}

i think there were some hidden junk characters were there, like next line(line breaks) or tab spaces etc.. that why it was giving error. so make sure "Details" key will be there in single line

Upvotes: 0

Andrew
Andrew

Reputation: 5083

The invalid characters are the line breaks in the "Detail" element. You'll need to escape them. Something like the solution presented here should work.

Upvotes: 5

morkro
morkro

Reputation: 4655

JSON only accepts single line Strings.

A work-around would be:

"Detail": [
    "<root>",
    ",<key keyname=\"state\">3</key>", 
    "<key keyname=\"oldState\">1</key>",        
    "<key keyname=\"currency\"></key>",
    "<key keyname=\"denomination\"></key></root>"
], 

You also have the option to replace line breaks into \n.

Upvotes: 6

Related Questions