I have a case that is how to find the value of a key that is in sekrip as follows:
JSON.parse({
"data": [
{
"id_user": "351023",
"name": "",
"age": "29",
"link": "http://domain.com"
}
]
});
The above data was obtained from:
<script type='text/javascript' src='http://domain.com/target.php'></script>
I want to get the value of the key "id_user", anyone can help me?
Thanks before.
Several issues here. Firstly, the method you're looking for is JSON.parse(), not parseJSON. Secondly, what you're providing to that function is already an object, not a JSON string, therefore it doesn't need to be deserialised as you can access it as you would any normal object:
var obj = {
"data": [{
"id_user": "351023",
"name": "",
"age": "29",
"link": "http://domain.com"
}]
}
console.log(obj.data[0].id_user);
First its JSON.parse. Second it needs to be a JSON string.
Fiddle: http://jsfiddle.net/5m5qs1x4/
var jsonData = JSON.parse('{"data": [{"id_user": "351023","name": "","age": "29","link": "http://domain.com"}]}');
document.getElementById('test').textContent = jsonData.data[0].id_user;
You need to parse JSON string and than, access to keys/index
var data = JSON.parse("{\"data\": [{ \"id_user\": \"351023\",\"name\": \"\",\"age\": \"29\",\"link\": \"http://domain.com\"}]}");
document.write(data["data"][0]["id_user"]);
Related
I have json response returned from a rest api as below
{
"data": [{ "id": "86", "name": "Hello", "last_name": "world" }],
"extra": { "message": "Hello", "additionalmessage": "world" }
};
I use jsonparse to convert it into object in javascript as below
var obj = JSON.parse(e.data)
When i access obj.extra.message it prints "Hello".
But when i try to access obj.data[0] , i get [object][Object] ,
seems like its taking "data" as a keyword?
How can i overcome this?
Note that you have your object inside an array.
Javascript doesn't show the whole object; you must use object's keys to access its data.
Obj.data[0] is the whole object.
It seems that your response is already JSON. So don't parse it again:
const data = {
"data":[
{
"id":"86",
"name":"Hello",
"last_name":"world"
}
],
"extra":{
"message":"Hello",
"additionalmessage":"world"
}
}
console.log(data["data"][0].name);
The parsing is working just fine; it's just that when you output the first element, you're just outputting the object, not one of its properties. The default toString on an object outputs [object Object]
You can try this:
var user = obj['data'][0];
console.log(user.name);
console.log(user.last_name);
Or try
JSON.stingify(obj.data[0])
here's how you can do it:
var obj = {
"data": [{ "id": "86", "name": "Hello", "last_name": "world" }],
"extra": { "message": "Hello", "additionalmessage": "world" }
};
console.log(obj["data"][0]["id"]);
JSON.parse Syntax: JSON.parse(text[, reviver]) Parameters: text-The string to parse as JSON. reviver- Optional If a function, this prescribes how the value originally produced by parsing is transformed, before being returned. Return value The Object corresponding to the given JSON text.
I really don't understand this. I have a JSON file that I need to use the data within to populate the DOM but I don't understand JSON.parse. When I tried to use this I used
var myData = JSON.parse({ "site": { "id": "example", "name": "example1" }...etc});
then tried to access it using dot notation.
console.log(myData.site.id);
I don't know what I'm doing, I've now figured out 200+ ways not to do it
JSON.parse expects a JSON string as its parameter, but you are passing javascript object literal, which is an object already and does not need parsing.
Depending on your use case you can either add quotes to make the parameter string:
var myData = JSON.parse('{ "site": { "id": "example", "name": "example1" }}');
Or don't use JSON.parse at all and you can work with your object directly.
var myData = { "site": { "id": "example", "name": "example1" }};
Pass JSON string to JSON.parse(yourJSONString) Then you can get values by call headers as follows.
var myRst = JSON.parse('{ "site": { "id": "example", "name": "example1" }}')
Then
myRst.site.id
var myRst = JSON.parse('{ "site": { "id": "example", "name": "example1" }}')
console.log(myRst.site.id)
when my ajax call completes an array of json is returned
for my angular data binding to work perfectly, i need to merge all values in to a single JSON file. I have tried $.extend(), it's giving following output
Need a solution for this
for example if my response looks like this:
[0:"{'test':'test'}", 1:"{'test':'test'}", 2:"{'test':'test'}",3: "{'test':'test'}"];
the output i need is :
{ test':'test', 'test':'test', 'test':'test', 'test':'test' }
Edit:
The final value will be associated to the ng-model automatically.
desired output example:
{
"unique_id": 172,
"portfolio": "DIGITAL",
"bus_unit": "dummy",
"project_phase": "",
"test_phase": "SIT",
"project": "Google",
"golivedate": "03/09/2016",
"performance": "Green",
"summary": "jgnbfklgnflknflk",
"last_updated": "",
"risks_issues": "gfmngfnfglkj",
"project_start": "03/16/2016",
"batchLast_run": "",
"custom_project": "1",
"test_execution_id": 5456,
"unique_id": 172,
"test_execution_id": 5456,
"pass": 8,
"fail": 8,
"blocked": 8,
"in_progress": 8,
"no_run": 8,
"not_available": 0,
"total": 8
}
From what I understand you are trying to convert array of Json data into one singel json data. So you have array of values but you would want all of them in one variable. Try this
var testData = ["{'test':'test'}", "{'test':'test'}", "{'test':'test'}", "{'test':'test'}"];
var finalData ="";
$.each(testData,function(index,value){
finalData += value +',';
});
finalData = finalData.replace(/\},\{/g,',').slice(0, -1);
document.write(finalData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Map just applies the function to every element in the array.
var arrayOfJSON = ...
var arrayOfObjects = arrayOfJSON.map(function (jsonString){
return JSON.parse(jsonString)
})
var jsonStringWithAllObjects = JSON.stringify(arrayOfObjects)
If you use underscore.js then can easily
like:
var list = [{"test1": "test1"}, {"test2": "test2"}, {"test3": "test3"}];
var newList = _.extend.apply(null,[{}].concat(list));
then output will be
{ test1: "test1", test2: "test2", test3: "test3" }
Iterate over the array, convert every value to a JSON object, concatenate and then convert to a string back.
If you need fo this more times, you probably should make this a function.
How to get value from [object Object] in javaScript.
i have a json response from php which i pass in javascript .
i want GPSPoint_lat,GPSPoint_lon all value.
var jArray = ;
var obj = JSON.parse(jArray);
i got [object Object] how i retrive the all value from obj.
my json string is-
{
"Account": "dimts",
"Account_desc": "Adminstrator",
"TimeZone": "Asia/Calcutta",
"DeviceList": [
{
"Device": "dl1pb1831",
"Device_desc": "DL 1PB 1831",
"EventData": [
{
"Device": "dl1pb1831",
"Timestamp": 1387790572,
"Timestamp_date": "2013/12/23",
"Timestamp_time": "14:52:52",
"StatusCode": 61472,
"StatusCode_hex": "0xF020",
"StatusCode_desc": "Location",
"GPSPoint": "28.52802,77.14041",
"GPSPoint_lat": 28.52802,
"GPSPoint_lon": 77.14041,
"Speed": 12.9,
"Speed_units": "km/h",
"Heading": 193.6,
"Heading_desc": "S",
"DigitalInputMask": 3,
"DigitalInputMask_hex": "0x03",
"Index": 0
}
]
},
{
"Device": "dl1pb7520",
"Device_desc": "DL 1PB 7520",
"EventData": [
{
"Device": "dl1pb7520",
"Timestamp": 1387790574,
"Timestamp_date": "2013/12/23",
"Timestamp_time": "14:52:54",
"StatusCode": 61472,
"StatusCode_hex": "0xF020",
"StatusCode_desc": "Location",
"GPSPoint": "28.56589,77.05268",
"GPSPoint_lat": 28.56589,
"GPSPoint_lon": 77.05268,
"Speed": 29.9,
"Speed_units": "km/h",
"Heading": 91.4,
"Heading_desc": "E",
"DigitalInputMask": 3,
"DigitalInputMask_hex": "0x03",
"Index": 0
}
]
},
Look at javascript tutorial
obj['key_name']
JSON objects work as an array. You can access to an element with a key:
obj['Account'] // returns dimts
obj.Account // works also
You should read some tutorial about it, like JSON: What It Is, How It Works, & How to Use It
Please retrive the value as
var jArray = <?php echo json_encode($_SESSION['return'] ); ?>;
var obj = JSON.parse(jArray);
var value=obj.Result;
I have zero experience in php so I don't know what's the resulting object from your first line of code. But assuming jArray is a json object with the structure defined in your question...you access its values as shown below...
jArray.Account;
jArray.DeviceList[0].Device; //access the device property of the first object in the DeviceList array
jArray.DeciveList[0].EventData.StatusCode;
This is my sample JSON file , which im trying to parse and read the values ....
C = {{
"Travel": {
"ServiceProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
},
"BusProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
}
}
}
I'm pretty new to JS , and i need to access the nested elements in a generic fashion.
Im not able to extract the details properly. Im getting stuck accessing nested the child elements.
The problem for me is that i wont always know the names of the "key's' to acess them , the JSON will be dynamic , hence i need a generic mechanism to acess the nested child elements. The Nesting can go upto 3 -4 levels.
what notation do we use to access the key / value pairs when the nesting is deep.
Any Help would be appreciated.
ater desirializing your object you can do this
var resultJSON = '{"name":"ricardo","age":"23"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key
alert(k + ' is the key)
}
you can do it using recursively offcourse like this - Link Here
the way is the same just adapt to your example
For dynamic access you can use brackets notation i.e. var json = {nonKnown: 1}; now you can access it like that:
var unknowPropertyName = "nonKnown";
var value = json[unknownPropertyName];
But if you can not even define dynamically name of the property, then you should use
for(variableName in json){
if(json.hasOwnProperty(variableName)){
console.log(variableName);
}
}
You should get the basic idea from this. Good luck