Cannot accurately parse this JSON in script? - javascript

var var1 = JSON.parse('[{"ItemId":1, "ItemName":"item 1\"", "Unit":"Nos","Remarks":null, "ConsumedQuantity":1.00},
{"ItemId":1253, "ItemName":"item 2", "Unit":"Nos", "Remarks":null, "ConsumedQuantity":1.00}]');
var1.forEach(function (e) {
Object.keys(e).forEach(function (key) {
if (e[key] == id) {
//doing some stuff here
}
});
});
This code works perfectly when the value in the JSON doesn't contain double quotes. This JSON is produced from a list of Model in MVC.
I use #Html.Raw(Json.Encode(ViewBag.materialDetails)) to convert the list to JSON. When there is a double quote, then it doesn't enter into the forEach.
Any help is appreciated :)

#Html.Raw(Json.Encode(ViewBag.materialDetails)) should return valid JSON data so you don't need to add ticks around it or JSON.parse it.
If you change
var var1 = JSON.parse('#Html.Raw(Json.Encode(ViewBag.materialDetails))');
to:
var var1 = #Html.Raw(Json.Encode(ViewBag.materialDetails));
it might work

Related

Replacing values in JSON object

I have the following JSON object data returned from my apicontroller :
[
{"id":2,"text":"PROGRAMME","parent":null},
{"id":3,"text":"STAGE","parent":2},
{"id":4,"text":"INFRA","parent":2},
{"id":5,"text":"SYSTEM","parent":3},
{"id":6,"text":"STOCK","parent":3},
{"id":7,"text":"DPT","parent":3},
{"id":9,"text":"EXTERNAL","parent":null}
]
I want to replace "parent":null with "parent":'"#"'
I have tried the code below, but it is only replacing the first occurrence of "parent":null. How can I replace all "parent":null entries?
$(document).ready(function () {
$.ajax({
url: "http://localhost:37994/api/EPStructures2/",
type: "Get",
success: function (data) {
var old = JSON.stringify(data).replace(null, "'#'"); //convert to JSON string
var new = JSON.parse(old); //convert back to array
},
error: function (msg) { alert(msg); }
});
});
Thanks,
You need to make the replace global:
var old = JSON.stringify(data).replace(/null/g, '"#"'); //convert to JSON string
var newArray = JSON.parse(old); //convert back to array
This way it will continue to replace nulls until it reaches the end
Regex docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Also, as a side note, you should avoid using new as a variable name as it is a reserved word in javascript and most browsers will not allow you to use it
#JonathanCrowe's answer is correct for regex, but is that the right choice here? Particularly if you have many items, you'd be much better off modifying the parsed object, rather than running it through JSON.stringify for a regex solution:
data.forEach(function(record) {
if (record.parent === null) {
record.parent = "#";
}
});
In addition to being faster, this won't accidentally replace other nulls you want to keep, or mess up a record like { text: "Denullification Program"}.

How to get the second data of this JSON in jQuery?

How can I get the second data of this JSON - I am beta. in jQuery?
{"alpha":["I am alpha"],"beta":["I am beta."]}
You can go through array and search for keys what you want... but dont forget to encode json string
$data= json.encode($input)
foreach($data as $key => $val)
{
if($key=='beta')
do something
else
do something else
}
I hope it help you.
Assuming that your json is in a string variable as:
var data = '{"alpha":["I am alpha"],"beta":["I am beta."]}';
You can parse the string as a json object and then access the content like this:
json = JSON.parse(data);
//or if you strictly need to use jQuery
json = $.parseJSON(data);
alert(json.alpha[0]);
alert(json.beta[0]);
If you don't know which is the json content you can iterate through json object like this:
for (var key in json) {
if (json.hasOwnProperty(key)) {
alert(key + " -> " + json[key]);
}
}
Finally I come up with this
Step 1: Json parsed,
Step 2 : Declared in another string
Step 3 : And then looped inside each entry
obj=JSON.parse(data);
var error_string='';
$.each(obj, function(entry) {
error_string+=obj[entry]+'<br/>';
});
$('#stage').html(error_string);
}
And then i got the values that is inside, Now i can able to get the values inside the object even for n numbers.

How to get array elements from json using javascript

I am trying to extract an array from my json string. Please help me. I have the following javascript code,
function lookup(inputString,autoSuggestionsList,TextFieldName)
{
autoSuggestionsListMain=autoSuggestionsList;
inputTextField=TextFieldName;
if(inputString.length == 0)
{
$('#suggestions').hide();
}
else
{
$.post("show_location_hint.php",
{ queryString: ""+inputString+"" },
function(data) { if(data.length >0) { } });
}
}
my show_location_hint.php file will echo the following json string
{"root": {"success":"1","message":"","data":{"locations":[a,b,c]}}}
how can I get the elements from the array locations?
please help me
Thanks
You can parse it to an array using JSON.parse():
var dataArray = JSON.parse(jsonString)
Then just simply do stuff like:
alert(dataArray.root.message)
Try this:
$.post("show_location_hint.php", { queryString: inputString }, function(data) {
if (data) {
var locations = data.root.data.locations;
}
});
Note however that your JSON format is not valid as, a, b, and c should be wrapped in double quotes. I'm guessing this is just a sample of your actual data though.
First your json is well formed. It should be:
{"root": {"success":"1","message":"","data":{"locations":["a","b","c"]}}}
and you can get data like this using jQuery:
var data = {"root": {"success":"1","message":"","data":{"locations":["a","b","c"]}}};
console.log(data.root);
console.log(data.root.success);
console.log(data.root.data);
$.each(data.root.data,function(index,item){
console.log(item);
});
Fiddle DEMO

Get json data from a file

I wan't to get data from a json file without knowing exacly where the data is:
I have this json
var names= [
{
"category":"category1" ,
"name1":"david",
"name2":"jhon",
"name3":"peter"
},
{
"category":"category2" ,
"name1":"Smith" ,
"name2":"Anna",
}
]
suppose i have a string variable:
var str='category2';
how can i get category2.name1 using the variable?
I don't want to use names[1].name1 because i don't know whats in str and i want to avoid using for loop.
There are some build-in functions that may help you. For example:
var matchingElements = names.filter(function(object, index, array) {
return object.category == str;
});
What you're looking for will always be in matchingElements[0].name1 if matchingElements.length > 0.

Remove Double Quotes at Begin & End from JSON Object/String or Java script Variable?

I'm getting a JSON Array of objects from servlet and trying to populate in a table control in java script.
Here is my code, for some reason it is putting double quotes at the beginning and End, which is not accepted by Table control for populating values. how can I remove this double quotes at beginning and End.
aData = [{"A":"one","B":"Two","C":"Three","D":"8","E":"No","F":"Business","G":"0",
"L1H":"Analytics"},{"A":"ones","B":"Twos","C":"Threes","D":"85","E":"Nos",
"F":"BusinessD","G":"0","L1H":"AnalyticsM"}]
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({modelData: aData});
var oTable=sap.ui.getCore().byId("id1");
oTable.setModel(oModel);
oTable.bindRows("/modelData"); // This static code of aData is working fine in
// my Table control of HTMl page.
//Here, i Wanted to get values dynamically from servlet and populate it in Table.
var global;
$.get('someServlet', function(data) {
var abc, xyz;
for(var i=0;i<(data.length);i++){
abc='{'+'\"A\":'+'\"'+data[i].A+'\"'+','+'\"B":'+'\"'+data[i].B+'\"'+',
'+'\"C\":'+'\"'+data[i].C+'\"'+','+'\"D\":'+'\"'+data[i].D+'\"'+',
'+'\"E\":'+'\"'+data[i].E+'\"'+','+'\"F\":'+'\"'+data[i].F+'\"'+',
'+'\"G\":'+'\"'+data[i].G+'\"'+','+'\"H\":'+'\"'+data[i].H+'\"}';
if (xyz===undefined)
xyz=abc;
else
xyz=abc+','+xyz;
global = xyz;
}
global="["+global+"]";
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({modelData: global});
var oTable=sap.ui.getCore().byId("id1");
oTable.setModel(oModel);
oTable.bindRows("/modelData");
});
//global="[{"A":"one","B":"Two","C":"Three"}...]"
//alert(global); Displaying without double quotes as expected.
//when I see the value in Chrome debugger double quotes are appearing at begin&End
So Finally I have value in global variable is, with double quotes.
//global="[{"A":"one","B":"Two","C":"Three","D":"8","E":"No","F":"Business","G":"0","L1H":"Analytics"},
{"A":"ones","B":"Twos","C":"Threes","D":"85","E":"Nos","F":"BusinessD","G":"0","L1H":"AnalyticsM"}]"
how can I get rid of this double quotes at beginning and end of this resultSet JSONArray Objects? If I put Alert, it is displaying without double Quotes. when I see this global variable in Chrome debugger, it is showing with Double quotes and failing to populate values in Table control. I'm having bit hard time with my code in populating values into Table control which are coming from Servlet in JSON format/String/Array. Please help.
Appreciate of any input and help.
You could call JSON.parse to parse your string into an object at the very end, that is:
global=JSON.parse("["+global+"]");
But instead of building yourself a string of JSON on the fly and then parsing it, it may just be simpler to set var global = []; and in your for loop do:
global.push({
Deals: data[i].Deals,
L1H: data[i].L1H,
L2H: data[i].L2H
});
Have you tried the following?
$.get('someServlet', function(data) {
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({modelData: data});
var oTable=sap.ui.getCore().byId("id1");
oTable.setModel(oModel);
oTable.bindRows("/modelData");
});
Don't build or parse json yourself. There are methods available to do it for you.
If your returned json only has an array of objects with the three properties Deals, L1H, and L2H, then data is what you want. If the returned json has more properties, and you only want those three, do this instead:
function(data) {
var arr = $.map(data, function(item, idx) {
return {
Data: item.Data,
L1H: item.L1H,
L2H: item.L2H
};
});
}
Your global variable is a JSON string. You don't need to construct a string. As far as I can tell, data is already a JavaScript object. I think this is what you want:
var global;
$.get('someServlet', function(data) {
global = data;
populateTable(global); // You could just as easily pass the data variable here
});
Since you are usig jQuery, try http://api.jquery.com/jQuery.parseJSON/ and it will return you an object instead.
Try with this:
var myJSON = eval( data );
where data is the string that the servelt has sent. Eval function makes the work, parse a string into JSON.
La forma correcta de eliminar las comillas es con
var obJason = eval( dataString );
var obj= "[{"ID":"786-000X-XX8","NAME":"LISANDRO ARCILES"}]";
aplicado la funcion eval()
obj= eval( obj);
lo tranforma al obejeto deseado de tipo Json

Categories