Get json data from a file - javascript

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.

Related

How to parse a jsonarray stored in a viewBag using jquery

I am not able to parse the jsonArray in the viewBag. I want to get the contents and then use them add options to a
Upon using a console.log I could see that my json is as follows :
So far I have an array with a single element
[
{
"BackgroundColor":null,
"BaseFormat":"PNG",
"ColorFormat":"RGB",
"ColorProfile":null,
"Density":"300",
"Extra_param":null,
"FileFormat":"JPG",
"PresetId":"2",
"Resolution":"",
"Quality":100
}
]
I have the contents in a variable as below:
var presetArray = #Html.Raw(Json.Encode(#ViewBag.user_doc_presets));
console.log(presetArray);
I want to get the BaseFormat and colorformat to be used into a select.
I tried some stackoverflow posts but they didn't help me.
If you have a link to an old post or a hint please do share.
#downvoters, Please let me know if you have any questions regarding this post instead of downvoting covertly.
Since it is of array type you can access it with its Index and here it is 0 as the array element is only one.
presetArray[0].BaseFormat
presetArray[0].ColorFormat
var presetArray = [{"BackgroundColor":null,"BaseFormat":"PNG","ColorFormat":"RGB","ColorProfile":null,"Density":"300","Extra_param":null,"FileFormat":"JPG","PresetId":"2","Resolution":"","Quality":100}]
console.log("Base Format: " + presetArray[0].BaseFormat);
console.log("Color Format: " + presetArray[0].ColorFormat);
I was missing a Json.Parse, which solved the problem
Please refer to
http://jsfiddle.net/jresdqw3/
var arr = [
{
"BackgroundColor":null,
"BaseFormat":"PNG",
"ColorFormat":"RGB",
"ColorProfile":null,
"Density":"300",
"Extra_param":null,
"FileFormat":"JPG",
"PresetId":"2",
"Resolution":"",
"Quality":100
}
];
alert(arr.length);
alert(JSON.stringify(arr).length);

How to read the values inside the json array

I have a json like
var obj={
"address":{
"addlin1":"",
"addlin2":""
},
"name":"sam",
"score":[{"maths":"ten",
"science":"two",
"pass":false
}]
}
Now when Iam trying to modify the json iam try an array variable and passing above json to that like
var data=JSON.parse(obj);
var json={};
json['name']=data['name'];
json['address']={};
json['address']['addressline1']=data['address']['addlin1'];
json['address']['addressline2']=data['address']['addlin2'];
json['marks']={};
json['maths']=data['score']['maths'];
For name and address I was able to form the json as i was expecting.But for marks I was unable.May be in obj json score values are in [ ]
So,when i console the json it is in this way
"name":"sam",
"address":{
"addresslin1":"",
"addresslin2":""
},
"score":{}
}
So how can I also read the values inside [] array.
Can someone help me
Thanks
json['maths']=data['score'][0]['maths'];
if you're not sure that data['score'] has any elements you can check prior to reading maths key:
if (data['score'].length) {
json['maths']=data['score'][0]['maths'];
}
data['score'] is an array, so you can't read it like that
json['maths']=data['score']['maths'];
you have to read it like that:
json['maths'] = data['score'][0].maths;
Also, obj is not a JSON, but a JavaScript object. You can use it directly.
json['maths'] = obj['score'][0].maths;
A JSON is a string, like that:
JSON.stringify(obj)
var json = "{"address":{"addlin1":"","addlin2":""},"name":"sam","score":[{"maths":"ten","science":"two","pass":false}]}";
create another json2 to contain score data then assign to json.
for example :
var json={};
json2 = {}
json2[0] = 1;
json2[1] = 2;
json[0] = json2;

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

jQuery getJSON print array where name is string

I have some good practice with using php and mysql, and am now starting with JSON.
I've made a simple json index containing paths to folders, and items inside them:
{ "foldery" : [
{
"foName": "website/img/bg",
"files" : [
"website/img/bg/bg1.jpeg",
"website/img/bg/bg2.jpg",
"website/img/bg/bg3.jpg",
"website/img/bg/bg4.jpeg"
]
},
{
"foName": "website/img/post1",
"files" : [
"website/img/post1/a.jpeg",
"website/img/post1/b.jpg",
"website/img/post1/c.jpeg",
"website/img/post1/d.jpg"
]
}
]
}
Now here is my jquery, for now returning a big mess of data, somewhere including the info about the contents inside:
$.getJSON("nameindex.json", function(data) {
console.log(data);
});
What I would like it to do, in mySql looks like this:
SELECT files FROM foldery WHERE foName = "website/img/post1"
Thus the result, would be an array containing all the files inside post1.
Unfortunately tho, after 2 hours of attempts I have nothing more than the simple console.log code.
Any help would be gladly appreciated
You need to iterate over your array and check forName to equality
function select(o, foName) {
var length = o.foldery.length;
for(var i = 0; i < length; i++){
if (o.foldery[i].foName == foName) {
return o.foldery[i].files;
}
}
}
var result = select(o, "website/img/post1")
console.log(result);
Result
[ 'website/img/post1/a.jpeg',
'website/img/post1/b.jpg',
'website/img/post1/c.jpeg',
'website/img/post1/d.jpg' ]

when saving an array of objects as a JSON, I need to use the following format in Sample.txt to not run into parsing errors:

when saving an array of objects as a JSON, you need to use the following format in Sample.txt to not run into parsing errors:
[{"result":"\"21 inches = 21 inches\"","count":1},{"result":"\"32 inches = 32 inches\"","count":2}]
I'm new to JSON and searching over this for since last 4 days. I tried different approaches of storing an array of objects but no success. My first and simplest try is like this:
function createData() {
//original, single json object
var dataToSave = {
"result": '"' + toLength.innerText +'"',
"count": counter
};
//save into an array:
var dataArray = { [] }; //No idea how to go ahead..
var savedData = JSON.stringify(dataToSave);
writeToFile(filename, savedData); //filename is a text file. Inside file, I want to save each json object with , in between. So It can be parsed easily and correctly.
}
function readData(data) {
var dataToRead = JSON.parse(data);
var message = "Your Saved Conversions : ";
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
}
To make an array from your object, you may do
var dataArray = [dataToSave];
To add other elements after that, you may use
dataArray.push(otherData);
When you read it, as data is an array, you can't simply use data.result. You must get access to the array's items using data[0].result, ... data[i].result...

Categories