Solomon Closson
Solomon Closson

Reputation: 6217

JSON Object Key with Quotes in them - How?

I have a list of names and am using them as keys to a json object, however, sometimes, the key might contain double quotes in them, like so:

var parts = {
    Expando Sleeve 1/4": [
    {
        id:"45", name:"TEST REPORT", partID:"4"
    },
    {
        id:"15", name:"01-077512", partID:"4"
    }]
};

So, the problem I'm facing here is I have the name as Expando Sleeve 1/4" which is what I need it to be, but I have it stored inside a hidden input element on the page like so: <input type="hidden" value="Expando Sleeve 1/4"" name="partName" />

So I do an ajax call, than use the value of the hidden input element... like so to add response values to a global parts array...

var $val = $('input[name="partName"]').val();

if (!parts.hasOwnProperty($val))
    parts[$val] = [];

parts[$val].push(response[$val]);

The problem here is that it adds the key into the json object parts like so:

parts[Expando Sleeve 1/4\"] instead of parts[Expando Sleeve 1/4"]. So I'm struggling on how to unescape the double quote in here and have the key set like this: Expando Sleeve 1/4".

How can I accomplish this?

Upvotes: 0

Views: 2988

Answers (4)

user4074041
user4074041

Reputation:

In chrome console all it's ok:

var obj = {};    
var val = "Expando Sleeve 1/4\"";
obj[val]="x";    
console.log(obj)
//console >> Object {Expando Sleeve 1/4": "x"}

another option:

var parts = {
    "Expando Sleeve 1/4\"": [
    {
        id:"45", name:"TEST REPORT", partID:"4"
    },
    {
        id:"15", name:"01-077512", partID:"4"
    }]
};    
console.log(parts)
//console >> 
//Object   Expando Sleeve 1/4": Array(2)
//__proto__    :    Object

Seems like jquery problem

UPD: It's html-safety "problem", worked solution:

$('<input value="escape&quot"/>').val()

Upvotes: 1

Rahul Mahadik
Rahul Mahadik

Reputation: 12271

Replace you double quote from value

<input type="text" name="name" value="&quot;YOUR_VALUE">

Upvotes: 0

aaronw
aaronw

Reputation: 156

You can use the character literal quote (') to save JSON keys as a string

var parts = {
    'Expando Sleeve 1/4"': [
    {
        id:"45", name:"TEST REPORT", partID:"4"
    },
    {
        id:"15", name:"01-077512", partID:"4"
    }]
};

Upvotes: 0

El Duderino
El Duderino

Reputation: 1392

Use a double quote HTML character &quot; in the JSON.

var parts = {
    "Expando Sleeve 1/4&quot;": [
    {
        id:"45", name:"TEST REPORT", partID:"4"
    },
    {
        id:"15", name:"01-077512", partID:"4"
    }];
};

Upvotes: 2

Related Questions