on 02-28-2014 12:48 PM
Hi,
How can a string be converted to a JSON object in SAPUI5 ?
Example : var mystr = ' [ { name : "Joe", last : "Doe"}, { name : "Jack", last : "Daniel" }]';
How do i convert mystr to a JSON object which can be used in a JSONModel?
$,parseJSON(mystr) or jQuery.parseJSON(myStr) do not seem to exist.
JSONModel.setJSON(mystr) too did not work.
Any pointers ?
regards,
sreeram
$.parseJSON should exist.
Try to change your json string to this since your string is not a valid json (you can check this here: ) JSONLint - The JSON Validator.
var mystr = '[{ "name" : "Joe", "last" : "Doe"}, { "name" : "Jack", "last" : "Daniel" }]';
Take a look here:
Greets,
ben
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
are you sure that you have this kind of string? I assume definition of name/last should be surrounded by quotes in order to have correct JSON model, like that:
var mystr = '[ { "name" : "Joe", "last" : "Doe"}, { "name" : "Jack", "last" : "Daniel" } ]';
here is working example:
Hi Sreeram,
when you want to use parseJSON you need a valid json string, and a valid json string requires the quotes for the name attributes. (well explained here: javascript - JSON syntax for property names - Stack Overflow)
I've just tested the code posted above locally with SAPUI5 Version 1.16 and it works well - the parseJSON exists as expected since it's part of JQuery since jquery version 1.4.1) so I'm not sure what's wrong with your installation...
greets,
ben
Simply use
var jsonObject = eval(mystr);
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Please do not!
Reasons why you should avoid eval are explained here:
Hi Ben, Chandra, Vladimir,
My mistake. As both Ben and Vladimir have pointed out, the parseJSON expects string with double quotes around the property names.
I came to the wrong conclusion, since the test object could be constructed in Javascript without the quotes. Also, the documentation and editor's choices did not have "parseJSON'.
Now, my code is working.
regards,
sreeram
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi,
you can do as below,
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData( [ { name : "Joe", last : "Doe"}, { name : "Jack", last : "Daniel" }] );
Regards,
Chandra
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
86 | |
23 | |
11 | |
9 | |
8 | |
5 | |
5 | |
5 | |
5 | |
4 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.