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']
Related
First year # coding, this is very basic code style for js. Everything I look at to research for help is usually to complex for me to adapt into my basic code. Currently I've got this array I've created, and I'm trying to, in the end game, print out the "course_number, course_title, course_unit" object values onto a page. I'm also trying to modify them as well, but deleting or changing the values.
I'm just trying to call to CIS:0 right now and it's coming up as undefined. Do I need to use Object.create(CIS.___) or am I missing something here. I can't use the "new" function instead of Object.create
Tearing my hair out.
var cuesta = {
BUS_ED: {
CIS: [{
"course_number": "231",
"course_title": "Fundementals of Computer Science 1",
"Course Unit": "4"
},
{
"course_number": "201",
"course_title": "Intro to Computer Science",
"Course Unit": "3"
},
{
"course_number": "201",
"course_title": "Discrete Structures",
"Course Unit": "3"
}
],
}
};
alert(CIS[0]["course_number"]); // coming out as undefined
sorry for the mess, it has to stay in this type of structure because we haven't advanced further.
Z
You need to access the variable then all the separate elements in the data structure. You've almost got it. First cuesta then BUS_ED is an object, and then the rest you've got.
alert(cuesta.BUS_ED.CIS[0]["course_number"]);
be careful when you use the term undefined as in javascript 'undefined' is a speical value, so you had me a little confused. undefind is not the same as is not defined. / yes, javascript is weird.
Correct:
alert(cuesta.BUS_ED.CIS[0]["course_number"]);
var cuesta = { // Object
BUS_ED: { // new Object in object
CIS: [{ // array of objects in object.
Hope this helps.
This may be a very simple question but I really can't seem to make it work.
I have several JSON lines and a notes array.
Using notes.push(JSONline) I am saving one JSON line per array position, I assume, so in the following manner:
//notes[1]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}
//notes[2]
{"id":"27","valuee":"134","datee":"2016-04-05T15:15:47.238+0100","id2":53}
//notes[3]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":52}
Here is my problem: I want to print one specific attribute, for example id from one specific JSON line in the array. How can I do this?
When I do console.log(notes) it prints all the JSON lines just as expected. But if I do console.log(notes[1]) it prints the first character of the JSON line in that position, not the whole line.
Similarly console.log(notes[1].id) does not print the id from the first JSON line, in fact it prints 'undefined'.
What am I doing wrong?
Thank you so much.
I'd recommend that you parse all the json when you are pushing to notes, like:
notes.push(JSON.parse(JSONLine))
If you are somehow attached to having json strings in an array instead of objects, which I wouldn't recommend, you could always just parse once you have the jsonLine id
JSON.parse(notes[id]).id
Basically, you want to use JSON.parse for either solution and I'd strongly recommend converting them to objects once at the beginning.
You need to remember that JSON is the string representation of a JS object. JS strings have similar index accessor methods to arrays which is why you can write console.log(notes[0]) and get back the first letter.
JavaScript doesn't allow you to access the string using object notation, however, so console.log(notes[0].id) will not work and the reason you get undefined.
To access the data in the string using this method you need to parse the string to an object first.
var notes = ['{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}'];
var note0 = JSON.parse(notes[0]);
var id = note0.id;
DEMO
This leaves the question of why you have an array of JSON strings. While it's not weird or unusual, it might not be the most optimum solution. Instead you could build an array of objects and then stringify the whole data structure to keep it manageable.
var obj0 = {
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
id2: 51
};
var obj1 = {
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
var arr = [obj0, obj1];
var json = JSON.stringify(arr);
OUTPUT
[
{
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
"id2": 51
},
{
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
]
You can then parse the JSON back to an array and access it like before:
var notes = JSON.parse(json);
notes[0].id // 26
That's because you have {"id": "value"... as a string in your key value pairs. "id" is a string so you can't reference it like a property. 1. use
var notes = JSON.parse(notes);
as mentioned in the comments by The alpha
or remove the quotes try
{id:"26", ...}
that's why notes[i].id is returning undefined
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.
I'm scratching my head here why I can't figure this out. It should be easy. I am trying to work with a Javascript object which looks like so:
Object {object: "clip", function: "list", data: Object, items: 1} (console log )
This Object is stored in a variable called data.
if I do var items = data.items I get the number I expect (1). What I cannot seem to get is what is in the data section.
The data.data logged to the console looks like this:
Object {Clipid: "1", ClipprojectID: "2", Clipnote: "This is a sample clip", Clippath: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer_480x270_h264aac.m4v", Clipduration: "33"…}
I would expect if I wanted the Clipid I would be able to do:
var Clipid = data.data['Clipid'] or data.data.Clipid; however this always comes up null.
I've tried a number of things, but nothing works. I'm sure it's something silly or small I'm missing but any insight is appreciated. Thanks!
If it helps the data comes from jQuery.parseJSON( jsonString )
Note ** If I do this:
var objd = data['data'];
var arv = $.map(objd, function (value, key) { return value; });
I am able to get values like arv[0] etc but I'd prefer to go by key if possible...
Note 2 - It's the JSON Formatting I'm decoding
Hey sorry about this, I noticed the encoding is borked. It looks like if I do:
console.log( data.data["\u0000Clip\u0000id"] ); it wotks! It must have to do with the json_encode.
There's a small typo I guess-
data.data.Clipid
note the small i
It looks like the data is an object, not a dictionary, so you would do var Clipid = data.data.Clipid; to get at the information inside.
You can't do data.data['Clipid'] because you named the attributes using string literals, and the proper syntax you used (data.data.ClipId) has a typo, as mentioned.
if your "Object" in the "data" variable, you just have to do
var clipid = data.Clipid;
var object = {object: "clip", function: "list", data: {Clipid: "1", ClipprojectID: "2", Clipnote: "This is a sample clip", Clippath: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer_480x270_h264aac.m4v", Clipduration: "33"}, items: 1}
console.log(object);
Object {object: "clip", function: "list", data: Object, items: 1}
console.log(object.data)
Object {Clipid: "1", ClipprojectID: "2", Clipnote: "This is a sample clip", Clippath: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer_480x270_h264aac.m4v", Clipduration: "33"}
console.log(object.data.Clipid)
1
This works fine for me, we would need to see your code to see why you are specifically having problems.
It had to do with the JSON encode method in PHP... All the answers stated was what I had tried and are correct, it was just a valid JSON string which had had unexpected unicode characters.
To fix it I needed to do this: $json = str_replace('\u0000', "", json_encode( $response )); Where response was my array of data to be cnverted
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.