After searching online and not finding anything, I decided to post here.
What I have so far:
JSON
I have a JSON file, with several list of words that I need to retrieve according to user input. They look something like this:
{
"length": 10,
"targetWords": {
"SOME_NAME": [
{
"words": [
"xyz",
"xyz",
"xyz",
"xyz",
"xyz",
"xyz",
"xyz",
"xyz",
"xyz",
"xyz"
]
},
{
"text": "Some example text",
"letter": "X",
}
],
}
localStorage input
I ask the user to choose an option and "record" that answer in a variable. Let's call it "userInput".
userInput = localStorage.getItem("something")
I get the JSON and pass it to a variable (I'm using Phaser Framework)
TARGET_SOUNDS_DATA = this.game.cache.getJSON('targetSounds')
What I want now is to access the values inside it. I can do it if I go about it like this:
TARGET_SOUNDS_WORDS_ARRAY = TARGET_SOUNDS_DATA.targetWords.SOME_NAME[0].words
But unable to do so if I use the user answer/input like this:
TARGET_SOUNDS_WORDS_ARRAY =TARGET_SOUNDS_DATA.targetWords.userInput[0].words
This way I only get undefined
So I know I'm doing something wrong but what?
Any help/hints are welcomed! Thanks for your time!
Cheers,
J
You can use square brackets to select a property with a variable
TARGET_SOUNDS_WORDS_ARRAY = TARGET_SOUNDS_DATA.targetWords[userInput][0].words
You have to parse it and then to get result based on userInput access it like this
TARGET_SOUNDS_WORDS_ARRAY =TARGET_SOUNDS_DATA.targetWords[userInput][0].words
As I understand, and maybe I'm wrong, localStorage is key/value storage only. You'll have to convert the json to a string, store it, then retrieve it and convert it back to an object when you want to use it.
Related
So I have to edit an entire array and decided to copy it from google, it returned to me this:
{
"name": "Tom",
"age": 20
}
...
Is it possible to copy the array without the "" around the object name? Or is there another way of doing this?
Use JSON.parse() to parse the data
https://www.w3schools.com/js/js_json_parse.asp
Unable to get certain values back from JSON.
I'd like to get result.datafeed[0].prod[0].vertical[0].deviceProductJson[0].product_brand when I call it I get undefined.
So I go to check out the structure in console which brings back the following.
console.dir(result.datafeed[0].prod[0].vertical[0].deviceProductJson[0]);
'{
"product_id": "1",
"product_name": "Name",
"product_brand": "Brand",
"product_brand_id": "4",
"product_type": "",
"product_type_id": "1"
}'
How do I access product_brand it always returns undefined instead of Brand ?
So I looped through the data thinking it was just an empty cell and all of them came back undefined, am I doing something wrong because I feel like I am making the right call as other pieces of data are being returned from archives in the same area.
let result = JSON.parse(result.datafeed[0].prod[0].vertical[0].deviceProductJson[0]);
console.dir(result.product_brand);
The result.datafeed[0].prod[0].vertical[0].deviceProductJson[0] holds a string value. thus, you get an undefined when you try to access it's attribute.
A simple and fast way to move ahead would be to do
var brand = JSON.parse(result.datafeed[0].prod[0].vertical[0].deviceProductJson[0])['product_brand']
How can I store an object/array in JavaScript Cookies?
I tried that simple code
var item = {
price: 200,
company: 'Microsoft',
quantity: 500,
code: 'm33'
}
console.log(item);
Cookies.set('item', item);
console.log(Cookies.get('item'));
It shows all the values in the first console message, but gives only "[object Object]" in the second. Looks like js-cookie cannot work with objects correctly. Is there any way I can fix that?
You are storing an object, and cookies are allowed text-only. Remember that cookies have a max-length of 4 KB, so you can't store a lot of information here (use localStorage instead).
To solve this problem, you must to stringify the json first:
Cookies.set('item', JSON.stringify(item));
And you'll store a stringified object. To access it then, you must to parse the string:
console.log(JSON.parse(Cookie.get('item')));
Just use:
Cookies.getJSON('item')
js-cookie has built-in support for JSON parsing as from version 2.0.0, there is no need to change how you set it. For more information, see https://github.com/js-cookie/js-cookie/tree/v2.1.0#json
In cookie you can only store string. So in order to store object first you convert your object into string. Using this plugin here is an example:
var people = [
{"id": 123, "name": "Mazahir Eyvazli"},
{"id": 128, "name": "Mayki Nayki"},
{"id": 131, "name": "Mike Shinoda"}
];
$.cookie("people", JSON.stringify(people));
If you want to access your people as an object from cookie
// $.cookie("people") will return people object as an string
// therefore we parse it to JSON object
var people = $.parseJSON($.cookie("people"));
// now we can access our object
people[0]["id"] // --> 123
people[1]["name"] // --> Mayki Nayki
I am trying to create a JSON object in the particular format
{ "id": 12234 , "name": "Alex" , "gender": "Male"}
// My code starts here
var number = userid; // alert(userid) is 12345
var name= nameuser; // alert(nameuser) is Alex
var g= gender; // alert(gender) is male
var userObj = { "id": number , "name": name , "gender":g}
I tried `JSON.stringify(userObj); ,
that returns the object type as
{"id":"12345" , "name":"Alex" , "gender":"Male"}
but this is not what I want as I want the number to be 12345 and not "12345".
also tried stringifying the fields inside the object like
{ "id": number , "name":JSON.stringify(name) ,gender: JSON.stringify(g)}
but when I do alert(userObj) my object type is Object object and this is not a format the server recognises.
I am sure there is a workaround for this but I am unable to figure one out
JSON works with strings exclusively. It's invalid to have anything other than a string, array, or other JSON object in JSON. That said, a "number" is not allowed; it needs to be a string. Whatever you are working with with the JSON later needs to be able to change the string back it to a number, if necessary. JavaScript usually does a good job of coercing these.
On the server side you can just do something like
obj = json_decode(source)
obj.id = (int)obj.id
I think that your solution will come down to what you want to DO with the JSON, rather than how you want it to be formatted.
If you're using it in other JavaScript code, then the JSON.parse method is going to take care of most of your issue on the other side (with automatic type-casting dealing with the rest).
If you're using it on the server-side, again, PHP or similar will decode the object appropriately.
And if it's a more-strict language on your server, all you need to do is remember which parameters need to be cast to boolean or to int/float.
The below code from your question is valid JSON.
{ "id": 12234 , "name": "Alex" , "gender": "Male"}
I am guessing that the problem you have is that your userid variable is a string, not a number. If so, try
var number = parseInt(userid, 10);
(The 10 parameter indicates that you are using base 10 numbers as opposed to something like binary or hex).
store the object type as one of the property and use it to convert the way you want.
I have a json output that looks like this.
{
"38467": {
"name": "Tony Parker",
"book": [
{
"title": {
"name": "MediaWorks"
},
},
],
}
"59678": {
"name": "Ray Thomas",
}
}
Actually json output is a lot bigger list. But I want to only save author's name and their publisher. I want save multiple individual records for a single model.
I am using jquery to assign input elements their values.
$('#Author' + i + 'Title').val(response...);
But it is not working.
I appreciate any help.
Thanks.
JSON is just javascript data - a javascript object. Assign the "decoded" JSON data to a variable (say var dat), then you can access members the normal object/array away: dat[38467]['name'] is Tony Parker and so on.
comment update:
once you've decoded/stored the data, you can use a regular javascript foreach loop to go over it:
for (var bookID in booklist) {
var author = booklist[bookID]['name'];
var title = booklist[bookID]['book'][0]['title']['name'];
// ...do stuff here...
}
There's nothing magical about JSON, it's just javascript data packed up for easy/clean transmission. Of course, if you're using a framework such as jQuery or MooTools, you'd be better off using their own .each() operators, otherwise you'll get various bits of useless fluff from the for() loop.
edit: fixed code sample as per marimuthu's comment (good catch, thanks).