String to JSON without JSON object

I am using an old version of javascript, therefore I could not use the JSON object to convert a String to JSON. However, in the java script school I found a snip of code that helped me. I share you:

<!DOCTYPE html>
<html>
<body>
 
<h2>Create Object from JSON String</h2>
 
<p id="demo"></p>
 
<script>
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
 
var obj = eval ("(" + txt + ")");
 
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
 
</body>
</html>

Analista/Desarrollador y cofundador de QBit Mexhico. Tecnologías utilizadas Android, Java (EJB, Servlets, Faces, Groovy & Grails, Maven, Swing), .Net (C#, VB, ASP, MVC), Delphi, Spring, Hibernate, DTSx, Oracle, T-SQL, Firebird, MySQL, MongoDB, NodeJs, ReactJs (Flux). Sistemas Operativos Mac, Ubuntu y Windows.

Twitter LinkedIn 

One thought on “String to JSON without JSON object

  1. The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *