cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Convert Text String to JSON object

Former Member
0 Likes
4,392

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

View Entire Topic
Former Member
0 Likes

$.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:

JSFiddle

Greets,

ben

Former Member
0 Likes

Hi Ben,

Thanks for the reply. I'm not really concerned about the format of the string.

I'm concerned with the string to JSON convertor API. parseJSON or setJSON.

As i mentioned earlier, $.parseJSON is not there. I may be missing some library ???

regards,

sreeram

vladimirs_semikins
SAP Champion
SAP Champion
0 Likes

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:

JS Bin - Collaborative JavaScript Debugging</title> <link rel="icon" href="h...

Former Member
0 Likes

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