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
Related
I have a very simple array (please focus on the object with "points.bean.pointsBase" as key):
var mydata =
{"list":
[
{"points.bean.pointsBase":
[
{"time": 2000, "caption":"caption text", duration: 5000},
{"time": 6000, "caption":"caption text", duration: 3000}
]
}
]
};
// Usually we make smth like this to get the value:
var smth = mydata.list[0].points.bean.pointsBase[0].time;
alert(smth); // should display 2000
But, unfortunately, it displays nothing. When I change "points.bean.pointsBase" to something without dots in its name - everything works.
However, I can't change this name to anything else without dots, but I need to get a value? Is there any options to get it?
What you want is:
var smth = mydata.list[0]["points.bean.pointsBase"][0].time;
In JavaScript, any field you can access using the . operator, you can access using [] with a string version of the field name.
in javascript, object properties can be accessed with . operator or with associative array indexing using []. ie. object.property is equivalent to object["property"]
this should do the trick
var smth = mydata.list[0]["points.bean.pointsBase"][0].time;
Try ["points.bean.pointsBase"]
If json object key/name contains dot......! like
var myJson = {"my.name":"vikas","my.age":27}
Than you can access like
myJson["my.name"]
myJson["my.age"]
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
So say I have a JSON object like this:
{"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"}
And I can't modify it when it is created. But I want to make it look like this:
{"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI", checked: true}
So how would I do that with javascript?
In the context of JavaScript, there's no such thing as a "JSON Object". What you've got there are JavaScript objects. JSON is a data interchange format that was of course derived from JavaScript syntax, but in JavaScript directly an object is an object. To add a property, just do so:
var object = {"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"};
object.checked = true;
Now, if what you've really got is a string containing a JSON-serialized object, then the thing to do is deserialize, add the property, and then serialize it again.
With the way your question is currently structured:
> myJson = {"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"}
Object {name: "asdf", quantity: "3", _id: "v4njTN7V2X10FbRI"}
> myJson.checked = true;
true
> myJson
Object {name: "asdf", quantity: "3", _id: "v4njTN7V2X10FbRI", checked: true}
But I bet you may have to decode and recode first with:
JSON.parse(myJson)
JSON.stringify(myJson)
The entire thing may look like
// get json and decode
myJson = JSON.parse(response);
// add data
myJson.checked = true;
// send new json back
$.post('/someurl/', JSON.stringify(myJson));
Let's assume i have JS code like this:
var foo = new Array('foo', 'bar');
var bar = new Array();
bar.push(foo);
console.log(bar);
The console log only gives me:
Array [ Array[2] ]
I am looking for way to get true log in console. In this case array with subarrays and so on. Something similar to PHP:
echo '<pre>' . print_r($bar, TRUE);
Use dir instead of log. It gives an interactive view.
Chrome/Opera/Firefox all allow for further inspection of arrays via console.log().
Try Firebug also for additional debugging ability.
If your browser supports it, you can also use the JSON.stringify() function. It's best explained with an example:
var a = [
"123",
{ "foo": "bar" },
[ "inner", "array", [ "inner-inner", "array-array" ] ]
];
console.log( JSON.stringify(a) );
// "["123",{"foo":"bar"},["inner","array",["inner-inner","array-array"]]]"
Basically the function converts objects into a JSON string format allowing you to see each object/array and all of it's sub-elements in a plan, string-like format.
Keep in mind that this method will only be effective if the object you are trying to view only contains simple types of data... Function definitions within objects and more complex built-in objects such as window or document will not yield useful information.
I am trying to figure out if I JSON.Stringify an object like this:
{"m_id":"xxx","record":
{"USER":"yyy","PWD","zzz","_createdAt":
11111."_updatedAt":00000},"state":"valid"}
and then try to JSON.Parse out only the USER and PWD, not have to just call the object, but go through stringify. how would that work?
thanks.
I'm not sure why you're talking about stringifying your object. You'd stringify it if you needed to send the data across a network or something, not when you need to manipulate it in JS.
...how do I extract the strings in {...USER: "aaa", PWD: "zzz"...}?
Assuming you have a variable referring to the object, something like the following (with or without nice line breaks and indenting to make it readable, and with or without quotes around the property names):
var obj = {
"m_id": "xxx",
"record": {
"USER": "yyy",
"PWD" : "zzz",
"_createdAt": 11111,
"_updatedAt": 00000
},
"state": "valid"
};
Then you can access the properties in the nested record object as follows:
console.log( obj.record.USER ); // outputs "yyy"
console.log( obj.record.PWD ); // outputs "zzz"
// etc.
(Note: in your question you had two typos, a comma that should've been a colon in between "PWD" and "zzz", and a dot that should've been a comma in between 11111 and "_updatedAt". There's no way that JSON.stringify() would have produced the string that you showed with those mistakes.)
If you want the strings "USER", "PWD" etc as an array, then use Object.keys.
If you want to iterate them, just use a normal for-in enumeration.
I might have misunderstood the question, but if I think it is what it is then try using
var tmp = JSON.parse(string_to_convert)
this should suffice to convert your string to a proper Javascript Object
Then you can do
for(var index in tmp){
console.log(tmp[index]);
}
and this should list all the keys on the first set of properties. If you want to do a nested thing, then use recursion on the properties. Hope this makes sense...