-2

I have a little problem in picking up the data from the JSON actually can get some data, however when you have the occurrence of "/_string" the script error.

example:

JSON

"results":[{
price_value_prices: 15.05
price_value_prices/_currency: "USD"
price_value_prices/_source: "$15.05" 
}];

AJAX

$.ajax({
  type: 'GET',
  url: $url,
  dataType: 'json',
  success: function (data) {
    data.results[$n].price_value_prices/_sources
  }
});

console log output

_sources is not defined

how can I solve this problem?

  • 4
    The problem is because your JSON is invalid - all keys and values must be wrapped in quotes, eg: `"price_value_prices/_source": "$15.05"`. If you fix that you can then access the property using `data.results[$n]['price_value_prices/_sources']` – Rory McCrossan Dec 19 '15 at 12:07
  • Possible duplicate of [How do I parse Json with an invalid character for a field name? e.g. { "file/folder": "/Shared/Salesforce/asdf.txt" } with Newtonsoft?](http://stackoverflow.com/questions/19865260/how-do-i-parse-json-with-an-invalid-character-for-a-field-name-e-g-file-fol) – diziaq Dec 19 '15 at 12:11

2 Answers2

5

First thing, your JSON is invalid without the quotes on the left side for the field names, so change it to:

"results":[{
  "price_value_prices": 15.05
  "price_value_prices/_currency": "USD"
  "price_value_prices/_source": "$15.05" 
}]

And then access it using the [] operator.

data.results[$n]["price_value_prices/_sources"]

You cannot use / because it is another operator. If you have / or . in your field names, it is wise to use the [] operator.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
2

Your JSON is invalid in four different ways:

  1. You have a property initializer outside of any object initializer.

  2. Property keys must be in double quotes in JSON.

  3. You must have commas between properties in an object.

  4. You have a ; at the end of it.

#2 would solve your / problem.

Here's a valid version:

{
    "results": [{
        "price_value_prices": 15.05,
        "price_value_prices/_currency": "USD",
        "price_value_prices/_source": "$15.05"
    }]
}

Assuming you parse that and assign the result to obj, you can access price_value_prices/_currency using brackets notation and quotes (any kind):

console.log(obj.results[0]["price_value_prices/_currency"]);
console.log(obj.results[0]['price_value_prices/_currency']);

Note the [0] after results, since it's an array with a single entry in it.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875