Converted JSON Array selection - javascript

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);
});
});

Related

javascript, how to iterate parsed json correctly

Hi I have a json response that I have to parse. I want to pull the data and insert it into inputs value (if it exists)
My json is like this:
{"id":4,"comb_name":"Monitor__C9cGTqnM7Trz","resolution":null,"attribute_val":3,"porte":4, "deleted_at":null,"created_at":"2017-11-13 10:10:25","updated_at":"2017-11-13 10:10:25"}
The code:
if(isset(jsobj)) {
var parsed = JSON.parse(jsobj);
console.log(parsed);
for (var property in parsed) {
if(parsed.hasOwnProperty(property)) {
var possible_input = '#pro_' + property;
if($(possible_input).length) {
var actual_input = $(possible_input);
actual_input.val(property);
}
}
}
}
It actually works, the only problem is that "property" are "attribute_val", not "3". What can I do to grab the value of the property?
Just use the property name to access the value
actual_input.val(parsed[property]);

Looping through JSON returning values

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);

Javascript: How to parse a json array without knowing the key name?

I want to parse the following json:
{"key_410441":{"hashId":"hash123","tube_id":"4accdefk31"}}
Where key_410441 is the entry's name representing the object's value, and the following array is the object's data.
How can I retrieve it's value?
function defined(json) {
for (var i in json) {
var objId = json[i]. ????
}
}
Like Robo Robok said, use Object.keys(object)
if your json look like {"key_410441":{"hashId":"hash123","tube_id":"4accdefk31"}}
function defined(json) {
var hashId = json[Object.keys(json)[0]].hashId
var tube_id = json[Object.keys(json)[0]].tube_id
}
}
you can use shortcut json[Object.keys(json)] because you have olny one object
key_410441
Object keys are returned in form of an array by Object.keys(object)
I suppose you are using jquery and ajax to get a json from an external file. Then the piece of code would be:-
$.getJSON("aa.json", function(data) {
var obj = Object.keys(data),
json = data[obj];
for(var s in json) {
console.log(json[s]);
}
});

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

How can I write an array to a file in nodejs and keep the square brackets?

I want to write a matrix to a .js file. When I use console.log(matrix) everything is fine but when I write it to the file it comes out differently.
var fs = require("fs");
var matrix = new Array(10);
for(var i=0;i<matrix.length;i++) matrix[i]=[];
for (var i = 0; i < 100 ; i++)
{
var n = i%10;
matrix[n].push(i);
}
console.log(matrix);
//write it as a js array and export it (can't get brackets to stay)
fs.writeFile("./matrixtest.js", matrix, function(err) {
if(err) {
console.log(err);
}
else {
console.log("Output saved to /matrixtest.js.");
}
});
So the console.log gives me [[0,10,20,30,...100],...,[1,11,21,31,...91]] and so on. But opening up matrixtest.js it's only this:
0,10,20,30,40,50...
All the numbers separated by commas with no brackets. How do I prevent it from converting to that format? Thank you.
When you are writing an Array to a file, it is getting converted to a string as JavaScript cannot figure out how to write an array as it is. That is why it loses the format. You can convert an array to a string like this and check
var array = [1, 2, 3, 4];
console.log(array.toString());
// 1,2,3,4
So, to solve this problem, you might want to convert it to a JSON string like this
fs.writeFile("./matrixtest.js", JSON.stringify(matrix), function(err) {
...
}
stringify it (JSON.stringify) before saving it then parse it (JSON.parse) when reading it back in.
fs.writeFile("./matrixtest.js", JSON.stringify(matrix), function(err) {
if(err) {
console.log(err);
}
else {
console.log("Output saved to /matrixtest.js.");
}
});
then when reading back in
var matrix = JSON.parse(contents);
The system doesn't know that you wanna store the array into the file with [].
It just puts the contents of the array to the file.
So, first you need to convert the data you wanna write to file into JSON format.
The JSON.stringify() method converts a JavaScript value to a JSON string
Then, write the JSON string to the file.
Then, while reading, use JSON.parse(). JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string
fs.writeFile('./matrix.js', JSON.stringify(matrix), function (err) {
if(err) {
console.log(err);
}
})
fs.readFile('./matrix.js', function(err, data) {
console.log(JSON.parse(data));
//Do whatever you want with JSON.parse(data)
});

Categories