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
Related
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
I've json which looks little complex array of json, I want to parse "1238630400000" and "16.10", like this I need all the values. I'm not getting how we can parse all these values.
This is the code I've tried but no luck:
for (var key in myJSON.Stocks) {
alert(myJSON.Stocks[key].stockPrice);
}
var myJSON = {
"Stocks": {
"stockPrice": [
[1238630400000, 16.10],
[1238716800000, 16.57],
[1238976000000, 16.92],
[1239062400000, 16.43],
[1239148800000, 16.62],
[1239235200000, 17.08],
[1239580800000, 17.17],
[1239667200000, 16.90],
[1239753600000, 16.81],
[1239840000000, 17.35],
[1239926400000, 17.63],
[1241049600000, 17.98]
]
}
}
Can someone help how can i get all these values?
You can get the values by doing a simple forEach on the stockPrice array
myJSON.Stocks.stockPrice.forEach(function(data) { console.log(data[0], data[1]); });
Here is the simplest way:
var csv = myJSON.Stocks.stockPrice.map((o)=>o.join()).join();
console.log(csv);
So I made this code in Nodejs:
var stemidLength= JSON.memberList.members[0].length;
for (stemidIndex = 0; stemidIndex < stemidLength; stemidIndex++) {
var steamID64Length= JSON.memberList.members[steamidIndex].steamID64.length;
for (steamid64Index = 0; steamid64Index < steamid64Length; steamid64Index++) {
steam.addFriend(steamID64[i]);
}
}
And I'm trying to extract the steamid64s from the xml page here: http://steamcommunity.com/groups/Valve/memberslistxml/?xml=1.
I already converted the xml page into a JSON array.
What is wrong in my code? Getting error:
cannot read property 'members' of undefined.
EDIT: The JSON extracted array: http://pastebin.com/FECXEKMD
Thanks.
The JSON object is a built-in object for parsing JSON and converting strings to JSON. It does not have a memberList property.
I'll refer to the result of the XML to JSON conversion as steamUsers.
The IDs can be found in steamUsers.memberList.members[0].steamID64. You can add the IDs with the code below:
xmlToJson(urlxml, function(err, data) {
if (err) {
return console.err(err);
}
var steamUsers = data;
steamUsers.memberList.members[0].steamID64.forEach(function(memberID) {
steam.addFriend(memberID);
console.log(memberID);
});
});
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"}.
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.