Ramya
Ramya

Reputation: 31

I want to remove double quotes inside a JSON string through regular expressions in javascript

I have a JSON something like this

{
      "DocumentID": 28663,
      "DocumentName": " Have a "HAPPY" and safe journey ",
}

I am getting error

Unexpected token H in JSON at position 315784

So I have to remove double quotes surrounding HAPPY.

How do I do this?

Upvotes: 1

Views: 893

Answers (3)

Anurag Awasthi
Anurag Awasthi

Reputation: 238

Obviously you can solve this without reg ex. Most probably you're parsing the JSON wrong way. But still anyway here's the code to replace double quote with single in json string

function passJSON_ItWillReplaceDoubleQuoteWithSingle(str){
  var firstDoubleQuoteFound = false;
  var escapeNextDouble = false;
  var newStr = "";
  for (var i = 0; i<str.length; i++){
    var s = str.charAt(i);
    if(s == '"' && !firstDoubleQuoteFound){
        firstDoubleQuoteFound = true;
        newStr += '"';
    } else if(s == '"' && firstDoubleQuoteFound && !escapeNextDouble){
        if( isNextNonSpaceAcceptable(str, i+1) ){
            newStr += s;
            firstDoubleQuoteFound = false;
        } else {
            escapeNextDouble = true;
            newStr += '\'';
        }
    } else if(s == '"' && firstDoubleQuoteFound && escapeNextDouble){
        newStr += '\'';
        escapeNextDouble = false;
    } else{
        newStr += s;
    }
  }
  return newStr;
}
function doubleQuoteReplaced(str){
    return str.replace(/"/g, "'");
}
function isNextNonSpaceAcceptable(str, i){
    for(var j=i ; j<str.length ; j++){
        var s = str.charAt(j);
        if( s==' ' || s=='\t')
            continue;
        if( s == '}' || s==',' || s == ':')
            return true;
        else
            return false;
    }
}

and here's how I checked

var str = "{\"some_key\" : \"some \"Happy\" people\", \"next_key\":\"Z\"}";
console.log(passJSON_ItWillReplaceDoubleQuoteWithSingle(str));

It will fail when there's comma or '}' or ':' just after double quote

Upvotes: 0

Dan H
Dan H

Reputation: 3623

Since you are using C# to encode. From the MSDN website:

Json.NET should be used serialization and deserialization. Provides serialization and deserialization functionality for AJAX-enabled applications.

http://www.newtonsoft.com/json

Using that library should guarantee you getting a valid JSON string instead of an invalid JavaScript serialization.

Upvotes: 2

LellisMoon
LellisMoon

Reputation: 5030

" Have a "HAPPY" and safe journey " is not a correct string, you should write something like this:

" Have a 'HAPPY' and safe journey " or ' Have a "HAPPY" and safe journey '

Upvotes: 1

Related Questions