Mi JSON está almacenado en MySQL como este ...
{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22}Cuando se devuelve como JSON de Express, se ve así...
[{"JSON":"{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22}"}]que es JSON válido según JSONLint.com
Lo que me sorprende es iterarlo en un javascript HTML ...
Tengo esto en Javascript....
fProfiles_JSON = JSON.parse(xhr.responseText); console.log('Type of '+ typeof fProfiles_JSON); //yields "object" console.log('My object', fProfiles_JSON); console.log('LENGTH ', fProfiles_JSON.length); // Yields "1"Entiendo que de alguna manera tengo que iterar sobre este tipo de objeto para obtener los valores de "perfil" y "recuento" pero, sinceramente, no estoy seguro de cómo, ya que el valor de longitud es "1". Sé que esto es probablemente muy simple y simplemente no lo estoy viendo. ¿Alguien me puede apuntar en la dirección correcta?
var obj = [{"JSON":"{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22}"}] // in this case we have to extract the string: var string = obj[0]["JSON"] var fProfiles = JSON.parse("[" + string + "]"); // as @Barmar pointed out, the string's content is not valid JSON. // so we add at beginning and end square brackets to get a list // of objects. FProfiles.length // should be 3 // and you can access the `count` and `profile` attributes.Json no acepta comillas simples por lo que deben ser reemplazadas
//xhr.responseText contents simulated with var resp = "[{\"JSON\":\"{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22}\"}]"; j = JSON.parse(resp); inner = j[0]['JSON'].replaceAll("'","\""); objs = JSON.parse("[" + inner +"]"); objs[0]Resultado:
Object { profile: "sweet", count: 38 } Como señaló @barmar, "arreglar" json con un analizador personalizado siempre es un riesgo.
Un intento un poco mejor podría ser reemplazar las comillas simples con expresiones regulares más específicas
# added possible 'key': 'value' at the end resp = "[{\"JSON\":\"{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22},{'key99': 'value99'}\"}]"; j = JSON.parse(resp); re3 = /[{]'/ig; re4 = /'[}]/ig; re1 = /'(, *|: *)'/ig; re2 = /' *: *([0-9])/ig; inner = j[0]['JSON'].replaceAll(re3,"{\"").replaceAll(re4, "\"}").replaceAll(re1, "\"$1\"").replaceAll(re2,"\":$1"); // "{\"profile\":\"sweet\", \"count\":38},{\"profile\":\"bitter\", \"count\":31},{\"profile\":\"green\", \"count\":22},{\"key99\": \"value99\"}" objs = JSON.parse("[" + inner +"]"); // Array(3) [ {…}, {…}, {…} ]