Search code examples
javascriptjqueryjsonslash

Json with slash in string


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?


Solution

  • 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.