Access JSON Array through Javascript - javascript

I have some JSON Data like this:
[{"2015-02-10": ["00:00","00:30","01:00","01:30","02:00","02:30","03:00","03:30","04:00","04:30","05:00","05:30","06:00","06:30","07:00","07:30","12-00","12-30","13-00","13-30","18:00","18:30","19:00","19:30","20:00","20:30","21:00","21:30","22:00","22:30","23:00","23:30"]},{"2015-02-17": ["00:00","00:30","01:00","01:30","02:00","02:30","03:00","03:30","04:00","04:30","05:00","05:30","06:00","06:30","07:00","07:30","12-00","12-30","13-00","13-30","18:00","18:30","19:00","19:30","20:00","20:30","21:00","21:30","22:00","22:30","23:00","23:30"]}]
Now I parse it in Javascript and tried to access the values of a specific date:
var hours = $.parseJSON('JSON STRING ...');
var date = "2015-02-10";
console.log(hours[date]);
But I always get "undefined" and I really don't know how I can access this

Your data is an array ([ ... ]) with an object inside it.
Try:
console.log(hours[0][date]);

Related

json.dumps returns the objects as a string instead of a JSON object

In the views.py:
data1 = Inventory.objects.values_list('product_number','amount') data = json.dumps(list(data1), cls=DjangoJSONEncoder).
I pass data as context to the html file.
In the HTML file, Using JS I access the JSON object with this code:
{{ data|json_script:"hello-data" }}
<script type="text/javascript">
var data = JSON.parse(document.getElementById('hello-data').textContent);
document.getElementById('id_line_one').onchange = function(event){
console.log(typeof data)
alert(data);
document.getElementById('id_line_one_unit_price').value = data[this.value];
};
</script>
I expect the var data to be a dictionary but it seems to be a String. Object.fromEntries is not working and I get the error Uncaught TypeError: Iterator value [ is not an entry object at Function.fromEntries (<anonymous>).
JSON.parse is removing the double quotation and I get [[1, 56000], [2, 55000]] but I am not able to access it as a dictionary. Whenever I use the index to access it, It returns the single characters as output instead of thinking of it as a dict object. How can I convert it into a dictionary? Thanks
The problem is that you are obtaining a list from the following line:
data1 = list(Inventory.objects.values_list('product_number','amount'))
Hence, you are just converting a list to JSON and, then, parsing this JSON, which yields a list.
Try to use the following instead:
from django.core.serializers.json import DjangoJSONEncoder
from django.core import serializers
data_obj_model = Inventory.objects.all()
data1=serializers.serialize('json', data_obj_model, cls=DjangoJSONEncoder)
Then, you can access, in your JavaScript code, all the fields of the model using data["fields"].field_of_interest.
Or you can also create a custom dictionary with the two fields you were interested in as follows:
data1 = dict(Inventory.objects.values_list('product_number','amount'))
This could be used as a dictionary in the JavaScript after parsing it.

Converting string to a valid JSON object

hey there i saw many questions about this topic but none of them fit my question.
i'm trying to use localStorage to store a user custom preferences, i try put an json object into a localStorage key and use it later on.
the object at the beginning looks like that:
Object {test: "{a:"b",c:"d"}"}
the JSON.parse method returns an error, what i done is that:
var local_storage = getAll();
$.parseJSON(JSON.stringify(local_storage.test.substring(0,0).substring(0,local_storage.length,-1)));
the output is :
{a:"b",c:"d"}
but i can't use it as local_storage.test.a why is that and what is the solution for that?
thx for the help :)
Edit!
Thanks to #Oli Soproni B, the solution is:
var key = {a:"b",c:"d"};
var l = JSON.stringify(key);
localStorage.setItem('test',l);
var local_storage = $.parseJSON(localStorage.getItem('test'));
console.log(local_storage);
console.log(local_storage.a);
// data
var k = {a:"b", c: "d"};
// stringify json
var l = JSON.stringify(k);
// set item to local storage
localStorage.setItem('test', l);
// get item to local storage and parse data
var local_storage = $.parseJSON(localStorage.getItem('test'));
console.log(local_storage);
Object {a: "b", c: "d"}
console.log(local_storage.a);
prints b
// or use
var local_storage = JSON.parse(localStorage.getItem('test'));
// in parsing the stringify json data
Localstorage stores string, not object. So you need to convert object to string while storing and converting it to object while retrieving.
To store:
localStorage.setItem("key",JSON.stringify(obj));
To retrieve:
obj = JSON.parse(localStorage.getItem(obj));
See DEMO here.
You used Json.stringify, because you need to store the data into localstorage as a string only.
you need to parse that again to JSON in order to use it as a JSON object,
but not like this
JSON.stringify(local_storage.test.substring(0,0).substring(0,local_storage.length,-1))
This tries to get a substring from your previously stored string, and again tries to stringify it.
You can get the stored string directly like this,
var local_storage = getAll();
var test=JSON.parse(local_storage.test);
And then use, as the test object, as test: {a:"b",c:"d"}

Show Json Object In TextBox

I have json returned from Database.I want to pick only one object Value and show it in the textbox. Here is my json.
[{
"ErrorMessage":"",
"ID":294,
"ExpenseID":0,
"EffectiveDate":"/Date(1262284200000)/",
"FormattedEffectiveDate":"01-01-2010",
"Perunit":null,
"VATRate":17.5,
"ChangedByID":1,
"ChangedByName":"superuser, superuser",
"Expense":null,
"ErrorSummary":null,
"ErrorList":[]
}]
I have Tried
var Jsoninvoice = JSON.stringify(data)
alert(Jsoninvoice.VATRate) and also alert(data.VATRate)
Thank you In advance.
You have an array containing 1 object. stringify turns this object into a string - you need it parsed so you can use it.
(I'm not sure if the object is parsed already, so to cover all bases, we'll parse it)
var Jsoninvoice = JSON.parse(data);
alert(Jsoninvoice[0].VATRate);
You have to specify the arrays index before you can access the properties.
It is already json object and stringify is not needed as #tymJV said you need to parse it if it is returned as string, just you need to access array item, as it is an array:
alert(data[0].VATRate)
SEE FIDDLE
You could use $.parseJSON(YOURJSON), and then use the keys to pull the data. Since it's in an array, you'll have to use [0] to pull the first item in the array (ie: your data).
Example
$(document).ready(function(){
var j ='[{"ErrorMessage":"","ID":294,"ExpenseID":0,"EffectiveDate":"/Date(1262284200000)/","FormattedEffectiveDate":"01-01-2010","Perunit":null,"VATRate":17.5,"ChangedByID":1,"ChangedByName":"superuser, superuser","Expense":null,"ErrorSummary":null,"ErrorList":[]}]';
var json = $.parseJSON(j);
alert("VATRate: "+json[0].VATRate);
});
Fiddle for reference

How to get an inner object literal value with javascript

After calling console.log(JSON.stringify(req.params)), I get a string with the following structure:
{"q":"{\"email\":\"mymail#mail.com\"}","apiKey":"1234"}
With console.log(req.params.q), I have this result: {"email":"mymail#mail.com"}.
But I get "undefined" if I try to view the email value with console.log(req.params.q.email) or console.log(req.params.q["email"])
What is the best approach to get that value?
You must JSON.parse that inner part :
var test = {"q":"{\"email\":\"mymail#mail.com\"}","apiKey":"1234"};
alert(JSON.parse(test.q).email);
alerts mymail#mail.com
Why?
Because test holds an javascript object where q holds a string, So you must parse that string if you want to extract the JSON values from that string.
It looks like req.params.q is a string: "{\"email\":\"mymail#mail.com\"}".
You need to parse that json then fetch the value.
req = {params: {"q":"{\"email\":\"mymail#mail.com\"}","apiKey":"1234"}}
JSON.parse(req.params.q)
> Object {email: "mymail#mail.com"}
JSON.parse(req.params.q).email
> "mymail#mail.com"

Parse codebird reply into a array (or acces to the json text into the codebird's reply)

I am trying to use codebird to get some data from twitter. I have a script in JavaScript.
My problem is that codebird's reply is an object and not a JSON. So I can't use eval() to get parse the json text in an array.
I just need to acces the json data.
Thank you in advance
var cb = new Codebird();
cb.setConsumerKey("", "");
cb.setToken('','');
cb.__call(
"search_tweets",
"q=Twitter",
function (reply) {
data = eval(reply) //parse the returned JSON to array
}
}
);
If you need to convert a JavaScript object into a JSON string you can use
data = JSON.stringify(reply)
But usually it's better to deal with object itself - e.g. you can iterate thru it's properties (creating your own array if needed)

Categories