How can I assign a JavaScript variable by parsing a JSON file? - javascript

I have a database server that will be running a script to generate this given file daily:
{"data": [
{"variable":"var1","value": "123"},
{"variable":"var2","value": "456"},
{"variable":"var3","value": "789"}]}
I am trying to parse this file to set three javascript variables for a HTML canvas element.
So far, I'm thinking I'll parse the JSON file
var JSONfile = './file.json';
var getData = JSON.parse(JSONfile);
Then a for loop to assign the variables
for (i = 0; i < getData.length; i++) {
var getData.variable=getData.Value;
}
And I'm hoping to get results of:
var var1 = 123;
var var2 = 456;
var var3 = 789;
But var getData.variable=getData.Value; breaks. What am I missing?

JSON.parse() expects a JSON string, when you are passing it a file.
The first thing you need to do is use AJAX to get the contents of the file into a variable. Either use a library like jQuery (see http://api.jquery.com/jquery.getjson/) or from scratch in JavaScript. But don't waste your time on the "from scratch" version unless you have to.
Use jQuery to get the contents of the file into an object, and pass the inner data (an array) to a function called doSomething():
$(function () {
$.getJSON("./file.json", function (data) {
}).success(function (data) {
myArr = data.data;
doSomething(data.data);
});
});
Here, you iterate through the passed array, which contains elements that have a .variable and a .value property. This writes both properties of each element to the console, for your viewing pleasure:
function doSomething(arr) {
for (i = 0; i < arr.length; i++) {
console.log(arr[i].variable + ': ' + arr[i].value);
}
}
You can also access the properties directly by the index as follows:
alert(jsonFromFile.data[2].variable); // Will alert "var3"
alert(jsonFromFile.data[2].value); // Will alert "789"

Related

Am I building the JavaScript objects correctly for a JSON string array?

In JavaScript I have the following code:
for (i = 1; i<3; i++)
{
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
}
// get ready for transport to server and display result of string
var data = JSON.stringify(tempObj);
console.info("info: " + data);
// post string to server
$.ajax
({
type: 'POST',
url: 'out.php',
data: {data: data},
success: function(msg)
{
alert(msg);
}
});
In out.php I try to determine the result back from the server. The code is as follows:
<?php
if (ISSET($_POST['data']))
{
echo "TRUE";
}
ELSE
{
echo "False";
}
var_dump($_POST['data']);
?>
I am getting this message, AJAX alert (msg) :
**True** string(42) ""question, [object Object], [object Object]""
Apparently this message is describing the string array being passed.
What I now need to do, if the format is correct, is to be able to access the string array - maybe with JSON_decode and identify properties of the array so that I can make insertions into a MySQL database.
Thanks for any AND all help...
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
First of all. If you just test this part in the console you will see that if you concatenate JS object and the string ',' you get the string "[object Object],[object Object]". You need to first stringify the JS object before concatenating it with strings.
Second I can really seem to understand your code but looping that code will just override those variables because they are declared in the loop so that doesn't seem correct. Probably you want to get the declarations out of the loop.
Otherwise it's kind of like this - you stringify the Js object and pass it as data to the ajax.
No. To build JSON, first build a valid structure, then use JSON.stringify on the result; don't convert to string while building the structure. connectJSON + passObj will force passObj to string, resulting in "[object Object]".
Instead:
var array = []; // <== An empty array
for (i = 1; i<3; i++)
{
// Push entries into the array
array.push({id:i, ask:check_a, description:check_b});
}
// Convert to JSON
var data = JSON.stringify(array);
Side note: The code in your question didn't declare i anywhere. If your real code doesn't, it's falling prey to The Horror of Implicit Globals.* Be sure to declare your variables. :-)
* (that's a post on my anemic little blog)
The issue is here var tempObj = tempObj + connectJSON + passObj;. You are concatinating objects and strings. In that case JavaScript will use Object.prototype.toString() first and then do the concatination. and Object.prototype.toString() in case of objects will produce [object Object]. To fix this you have to create an array like below.
var tempObj = [];
for (i = 1; i < 3; i++) {
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {
id: i,
ask: check_a,
description: check_b
};
tempObj.push(passObj);
}
Also, you can skip JSON.stringify() and directly submit the JS object.
I'm trying to understand how is this deceleration :
var tempObj = tempObj + etc...;
possible ?
you cant set the value of something you just declared,
to the same thing you just declared .

Turn a json object string into value

I am writing a function that takes a string, splits it, and the uses json[key][key2][key3] formatting. The problem is n is potentially infinite (not literally but needs to written that way)
function getJsonValue(json,string) {
var vals = string.split(".");
var x = vals.length;
var string = '';
while (x != 0) {
string += "['"+vals[(vals.length-x)]+"']"
x--
}
return string;
}
That will produce, for example: "['condition']['item']['condition']['temp']"
I need to extract a value from that by attaching it to a json object, like
json"['condition']['item']['condition']['temp']"
But I don't know how or if that is even possible.
Edit:
The problem is I need any value from a config file to be passed in and then parsed from a returning function. I.e. User knows the value will be condition.item.condition.temp for this specific query. I am trying to write one function that covers everything and pass in config values for what I know to be the output. So, on one query, I might want the condition.item.condition.temp value and on another I might want condition.wind.chill .
I'm not sure if I understand 100% what you're trying to do, but if you're receiving a JS object json and a string in the format field1.field2.field3 and trying to get the value of json.field1.field2.field3 then you can do something like this:
function getJsonValue(json,string) {
var vals = string.split(".");
for (var i = 0; i < vals.length; i++) json = json[vals[i]];
return json;
}
It would work like this for a given object:
var obj = { field1: { field2: { field3: "Hello!" } } };
var res = getJsonValue(obj, "field1.field2.field3");
console.log(res); // prints Hello
See lodash get
_.get(json, 'key1.key2.key3')
you can build the "path" from your current code and ask lodahs to get the value out for you.
What about doing an eval?
var json = {
'one': {
'two': {
'three': {
'four': 4
}
}
}
};
alert(eval("json['one']['two']['three']['four']"))

how to parse json array

I'm trying to parse something like this
{
"popular result":[
{"term":"Summer","url":"http://summer.com"},
{"term":"Autumn","url":"http://autumn.com"},
{"term":"spring","url":"http://spring.com/"},
{"term":"winter","url":"http://winter.com/"}]
}
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i = 0; i < json.length; i++) {
$.each(myJson.i, function (key, value) {
alert(value.term);
});​
}
});
});
</script>
but nothing happened! Because is array in array! Please let me know how to do this
Arrays and objects are different things. You will want to investigate them tons more before things get really challenging.
Assuming json really does equal the object you provide (in JSON those show up as {}), then json['popular result'] (you could use a . if there wasn't a space) is the array (in JSON those show up at []) you want to traverse.
For some reason, this confusion got you looping over an object (not going to get you anywhere as length is rarely defined for it) and then (ignoring the typo on myJson), you started looping over something that didn't exist (which didn't crash b/c it never got there).
Cleaning it up...
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i=0;i<json['popular result'].length;i++) {
alert(json['popular result'][i].term + ' points to the URL ' + json['popular result'][i].url);
}
});
});
</script>
Notice how the alert references the json object (that's your variable name), the popular result array, then [i] is the "row" in that array, and the term/url element of the object on that row.
NOTE: Running something with a ton of alerts as you're debugging is annoying. Check out console.log.
You don't need $.each and you need to loop over the array set as the value of popular result which is inside a containing object.
$.getJSON('/Controls/GetPopularSearches', function (json) {
var arr = json['popular result'];
for (var i = 0, l = arr.length; i < l; i++) {
console.log(arr[i].term);
}
});
Demo.
Check this fiddle
var jsontext =
'{"popularresult":[{"term":"Summer","url":"http://summer.com"},{"term":"Summer","url":"http://summer.com"}]}';
var getContact = JSON.parse(jsontext);
for (i = 0; i < getContact.popularresult.length; i++) {
alert(getContact.popularresult[i].term);
}
http://jsfiddle.net/ae8gd/
If you get the jsonObject as shown then
var JsonArray=json.popular; //get jsonArry
$.each(JsonArray,function(i,val){
// do logic
});
To parse json use JSON.parse();

How to return all objects in javascript array

I have a variable that is created by Flowplayer and available via javascript. If I write the variable to the page directly it just returns 'object Object' so I am assuming this is an array. If I don't know the names of any of the objects inside the array, how can I parse out the data inside?
I know I am missing something really fundamental here, but I don't think I have ever had to get data from an array not knowing what it contains.
Notes:
What I am trying to do is get the onCuePoint caption data embedded
into an RTMP video stream
.valueOf() returns the same thing
Here is the code I am using that returns 'object Object':
streamCallbacks: ['onFI'],
clip:
{
live:true,
provider: 'rtmp',
autoPlay: true,
url:'test1',
onFI:function(clip, info)
{
document.getElementById("onFI").innerHTML += "Data: " + info;
}
}
Thank you
If what you are asking is how you iterate over the contents of an array, you can do so in plain javascript like this:
var arr = [1,2,3];
for (var i = 0; i < arr.length; i++) {
// arr[i] is each item of the array
console.log(arr[i]);
}
Just because something is of type Object does not necessarily mean that it's an array. It could also just be a plain object with various properties on it. If you look at the info argument in either the debugger or with console.log(info), you should be able to see what it is.
You need to iterate through your array and get the results one by one, replace your onFI function with this :
onFI:function(clip, info)
{
var data = "";
// For each value in the array
for (var i = 0; i < info.length; i++)
{
// Add it to the data string (each record will be separated by a space)
data += info[i] + ' ';
}
document.getElementById("onFI").innerHTML += "Data: " + data;
}

Javascript help setting/getting local storage data for each input element

I've been working on this, and it's very nearly working. I have a feeling that the setInterval inside the loop is something that can't be done, or isn't working. Without the setInterval and the final 'if' statement, it loops through the elements perfectly and adds a className to each if I set it to. Here's my script if anyone can advise as to where I am going wrong:
(function() {
var localStorageID = document.getElementById('local-storage');
var inputTags = ['input', 'textarea', 'select', 'button'];
// Loop through all the input tags on the page
for(var i = 0; i < inputTags.length; i++) {
// Create a variable that matches input tags inside our #localStorage
var localStorageTag = localStorageID.getElementsByTagName(inputTags[i]);
var formData = {};
for(var z = 0; z < localStorageTag.length; z++) {
formData[localStorageTag[z].name] = localStorageTag[z].value;
}
localStorage.setItem('formData', formData);
if(localStorage.getItem('formData')) {
// Try to achieve something
}
}
})();
You cannot store objects in localStorage. They must be strings. Convert the object to a string using JSON.stringify(), then JSON.parse() the string when retrieving from localStorage.
EDIT: for example:
localStorage.setItem('formData', JSON.stringify(formData));
var fd= JSON.parse(localStorage.getItem('formData'));
if(fd) {
// Try to achieve something
}

Categories