0
$scope.partsLinesTest = data[0].instock; // this is getting the JSOn data 
from my http request

for(var i=0; $scope.partsLinesTest.length > 0; i++) {
 //$scope.partsLinesTest =  $scope.partsLinesTest[0].instock;
console.log($scope.partsLinesTest.replace(/['{[\]}']/g,''))
var str = $scope.partsLinesTest;
$scope.partsLinesStock = str.replace(/['{[\]}']/g,'');
}

The Json data is somewhat formatted as below, my problem is with instock due to the extra regular brackets and curly braces which is why I thought using RegEX would solve problem, however I can't seem to iterate correctly through the data and post it back into the view, also I'm using Angular

var test = [
  {
      "id": 1,
      "title": "This is a document",
      "desc": "PO",
      "date": "2017-01-15",
      "instock": "[{'branch': 'Edmonton', 'quantity': 2}]"
  }
R. Richards
  • 24,603
  • 10
  • 64
  • 64
Darren
  • 1
  • 2

3 Answers3

0

A working temporary solution (no, better, a temporary workaround) would be to use Javascript's eval() function (which you should never do on a production system because it opens up security holes!):

var test = [
  {
      "id": 1,
      "title": "This is a document",
      "desc": "PO",
      "date": "2017-01-15",
      "instock": "[{'branch': 'Edmonton', 'quantity': 2}]"
  }]
  
console.log(eval(test[0].instock))
console.log(Array.isArray(eval(test[0].instock)))

As @Quentin pointed out, the correct solution would be to make the server emit correctly formatted JSON (which would require replacing the single quotes ' by escaped double quotes \").

Please read about why using eval() is strongly discouraged: Why is using the JavaScript eval function a bad idea?

connexo
  • 53,704
  • 14
  • 91
  • 128
0

If it's JSON-esque you know it will have , and : dividing keys and values. I would start by cleaning out all other characters and splitting it on those:

var jsonString = "[{'branch': 'Edmonton', 'quantity': 2}]"
var cleaned = jsonString.replace(/[^a-zA-Z0-9:,]/g,'')
  //"branch:Edmonton,quantity:2"

var splitIntoKeyVal = cleaned.split(',').map(function(row){ return row.split(':')})
  //[["branch","Edmonton"],["quantity],2]]
var json = {}

splitIntoKeyVal.forEach(function(row){
  json[row[0]] = row[1]
})

If you think your values might have : or , in them, you might have to do some other regex trickery.

nbwoodward
  • 2,816
  • 1
  • 16
  • 24
-1

In order to get the quantity you must parse the data.instock json.

var data = {
     "id": 1,
     "title": "This is a document",
     "desc": "PO",
     "date": "2017-01-15",
     "instock": '[{"branch": "Edmonton", "quantity": 2}]'
};

    
var stock = JSON.parse(data.instock);

console.log(stock[0].quantity); 
//$scope.partsLinesStock = stock[0].quantity;
michaelitoh
  • 2,317
  • 14
  • 26