Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaning strings to be valid JSON values

Tags:

json

c#

I want to clean strings that are retrieved from a database.

I ran into this issue where a property value (a name from a database) had an embedded TAB character, and Chrome gave me an invalid TOKEN error while trying to load the JSON object.

So now, I went to http://www.json.org/ and on the side it has a specification. But I'm having trouble understanding how to write a cleanser using this spec:

string

  • ""
  • " chars "

chars

  • char
  • char chars

char

  • any-Unicode-character- except-"-or--or- control-character
  • \"
  • \\
  • /
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u four-hex-digits

Given a string, how can I "clean" it such that I conform to this spec?

Specifically, I am confused: does the spec allow TAB (0x0900) characters? If so, why did Chrome given an invalid TOKEN error?

like image 699
Jeff Meatball Yang Avatar asked Jun 28 '10 14:06

Jeff Meatball Yang


People also ask

How do I make sure JSON is valid?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.

What does a valid JSON string look like?

A JSON string contains either an array of values, or an object (an associative array of name/value pairs). An array is surrounded by square brackets, [ and ] , and contains a comma-separated list of values. An object is surrounded by curly brackets, { and } , and contains a comma-separated list of name/value pairs.

Is a string a valid JSON body?

Yes, in most contexts. It is valid JSON syntax representing a JSON value.

What are valid JSON values?

Valid Data Types In JSON, values must be one of the following data types: a string. a number. an object (JSON object) an array.


2 Answers

Tab characters (actual 0x09, not escapes) cannot appear inside of quotes in JSON (though they are valid whitespace outside of quotes). You'll need to escape them with \t or \u0009 (the former being preferable).

json.org says an unescaped character of a string must be:

Any UNICODE character except " or \ or control character

Tab counts as a control character.

like image 100
Joey Adams Avatar answered Oct 03 '22 09:10

Joey Adams


This maybe what you are looking for it shows how to use the JavaScriptSerializer class in C#.

How to create JSON String in C#

like image 33
Rodney S. Foley Avatar answered Oct 03 '22 08:10

Rodney S. Foley