I have the following json which is returned by Influxdb which I can decode with PHP with out any issue i.e I use the following code:
$json_result = json_decode($json_result, true);
$http_result_series_0 = $json_result["results"][0]["series"][0] ["values"][0][5];
Now I would like to do the decoding with javascript in order to dynamically fill a table. But no matter how I try to do it, it's not working. I know that there's a similar way in javascript to decode the Array i.e:
json_result.results[0].series[0].values[0][5]
The json:
"{
"results": [
{
"statement_id": 0,
"series": [
{
"name": "default_lte_stick_1_test.com_http_response",
"tags": {
"server": "https://twitter.com"
},
"columns": [
"time",
"host",
"http_response_code",
"method",
"response_time",
"result",
"result_code",
"result_type",
"status_code",
"tag1",
"tag2"
],
"values": [
[
"2018-10-12T11:19:12Z",
"xps",
200,
"GET",
1.358607871,
"success",
0,
"success",
"200",
"test.com",
"LTE"
]
]
},
{
"name": "default_lte_stick_1_test.com_http_response",
"tags": {
"server": "https://google.com"
},
"columns": [
"time",
"host",
"http_response_code",
"method",
"response_time",
"result",
"result_code",
"result_type",
"status_code",
"tag1",
"tag2"
],
"values": [
[
"2018-10-12T11:19:10Z",
"xps",
301,
"GET",
0.051518655,
"success",
0,
"success",
"301",
"test.com",
"LTE"
]
]
},
{
"name": "default_lte_stick_1_test.com_http_response",
"tags": {
"server": "https://amazon.com"
},
"columns": [
"time",
"host",
"http_response_code",
"method",
"response_time",
"result",
"result_code",
"result_type",
"status_code",
"tag1",
"tag2"
],
"values": [
[
"2018-10-12T11:19:11Z",
"xps",
301,
"GET",
0.536477796,
"success",
0,
"success",
"301",
"test.com",
"LTE"
]
]
}
]
}
]
}
"
What I'm doing wrong? Every help is appreciated. Thanks!
EDIT:
The Influxdb API returns a pretty formated JSON. Currently I output the whole JSON with:
var json_result = '<?php echo $javascript_json_result;?>';
document.getElementById("jsonoutput").innerHTML = JSON.parse(json_result);
which outputs the whole json. But I would like to output only single values.
document.getElementById("jsonoutput").innerHTML = json_result.results[0].series[0].values[0][5]
trhows the following error:
e2e_check_new.php:172 Uncaught TypeError: Cannot read property '0' of undefined at e2e_check_new.php:172
What I'm doing wrong?
var json_result = '<?php echo $javascript_json_result;?>';
You are trying to output the JSON as a string in JavaScript by wrapping it in ' but you aren't escaping any of the characters in the JSON which have special meaning in JavaScript (like \ or a new line or ' - it looks like you definitely have at least new lines in your JSON).
Don't try to generate a string of JSON. Just output the JSON directly so it will be treated as a JavaScript object literal.
var my_object = <?php echo $javascript_json_result; ?>;
document.getElementById("jsonoutput").innerHTML = my_object;
… of course, this will convert the object to the string [Object object] which isn't useful. You can deal with the data structure in the usual ways though (i.e. access properties etc).
Related
I have a json collection stored as {"books": [{...}, ... ]} in a file. "books" is a list of json objects where each is a book. For example:
{
"books": [
{
"items": [
{
"id": "jD8iswEACAAJ",
"volumeInfo": {
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0984782850"
},
{
"type": "ISBN_13",
"identifier": "9780984782857"
}
],
},
}
]
},
]
}
I have a need to read the json using _.where, specifically search every item in the collection for the "identifier" value of "type": "ISBN_10". Then return the full json object aka {"items": [...]}.
Suppose req.params.id is the "identifier" value (i.e. 0984782850).
This piece of code is not working
var _ = require('underscore');
...
app.get('/api/books/:id', function(req, res) {
var book = _.where(booksData.books.items[0].volumeInfo.industryIdentifiers[0], {identifier: req.params.id});
res.json(book);
});
it is returning
TypeError: Cannot read property '0' of undefined at position 43
The file has valid json, I have tried
var book = _.where(booksData.books, {items[0].volumeInfo.industryIdentifiers[0].identifier: req.params.id});
which also does not work
There is always one item in "items" and the ISBN_10 identifier is the first item in "industryIdentifiers" hence items[0].volumeInfo.industryIdentifiers[0].identifier
What am I doing wrong?
*EDIT: I tried with industryIdentifiers, but response is [ ]
Don't use industryIdentifiers[1]. You want to search the entire industryIdentifiers array, not a single object.
var book = _.where(booksData.books[0].items[0].volumeInfo.industryIdentifiers, {identifier: req.params.id})[0];
You also need books[0], since books is also an array.
const booksData = {
"books": [
{
"items": [
{
"id": "jD8iswEACAAJ",
"volumeInfo": {
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0984782850"
},
{
"type": "ISBN_13",
"identifier": "9780984782857"
}
],
},
}
]
},
]
};
var book = _.where(booksData.books[0].items[0].volumeInfo.industryIdentifiers, {identifier: "0984782850"})[0];
console.log(book);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
A front-end developed is sending a array of data formated as a JSON object with an Ajax call.
The json object looks like this:
{
"name": " Test Name ",
"image_url": "test URL",
"include": [
"1"
],
"dimension": [
null
],
"media_type": [
null
],
"match": [
"1"
],
"content": [
"test content"
],
"sorting": {
"rating": "50",
"language": "50",
"CS Weight": "50",
}
}
How I can read it in my PHP controller. Can I just get it just this way:
$data = $_POST;
Because the variable that contains the JSON object in this case has no name, I cannot get it this way
$data = $_POST['data']
Edited Part
From the front-end, the data is sent this way:
sendAjax: function(value, url, callback){
xhr = $.ajax({
type: 'POST',
url: url,
data: value
}).done(function(message){
callback(message);
}).fail(function(jqXHR, textStatus){
console.log('failed to submit form, error type: '+textStatus);
});
}
Read it from the script's input, which is where you can get the "raw" POST data:
$json = file_get_contents('php://input');
$data = json_decode($json);
This should work assuming you're using jquery on your front end. Just paste this into your javascript console and run it (make sure you replace the path with your web address. The parameters should come through correctly.
data = {
"name": " Test Name ",
"image_url": "test URL",
"include": [
"1"
],
"dimension": [
null
],
"media_type": [
null
],
"match": [
"1"
],
"content": [
"test content"
],
"sorting": {
"rating": "50",
"language": "50",
"CS Weight": "50",
}
}
$.ajax({url:'/YOUR/PATH/HERE', data: {data: data}, type: 'post', dataType: 'json'})
Occurred to me after posting, are you asking how do you parse the JSON once received or how to get it to show in the $_POST hash?
I've tried 100 different things, and spend days looking through Google and Stackoverflow, but I can't find a solution to this problem. Everything I call after the body of this API response returns undefined!
The response from Facebook SDK looks like this:
[
{
"body": "[
"data": [
{
"name": "Larry Syid Wright",
"administrator": false,
"id": "xxx"
}, {
"name": "Melissa Long Jackson",
"administrator": false,
"id": "xxx"
}, {
"name": "Charlotte Masson",
"administrator": false,
"id": "xxx"
}
],
"paging": {
"next": "url"
}
]"
},{
"body": "{
"data": [
{
"id": "xxx_xxx",
"message": "In honor of Halloween, how many of you have your own ghost stories? Who believes in ghosts and who doesn't?",
"type": "status",
"created_time": "2014-10-31T20:02:01+0000",
"updated_time": "2014-11-01T02:52:51+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Joe HerBatman Owenby Jr."
}
],
}
"paging": {
"cursors":
{
"after": "xxx",
"before": "xxx"
}
}
}
},{
"id": "xxx_xxx",
"from": {
"id": "xxx",
"name": "Jessica Starling"
},
"message": "Watching the "Campaign" and I can't help but notice what a fantastic job they did (Will ferrell and all) with that North Carolina accent! Ya'll know we sound different than other southern states ;)",
"type": "status",
"created_time": "2014-11-01T02:36:21+0000",
"updated_time": "2014-11-01T02:36:21+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Scott Williams"n
}
]
}
}
],
"paging": {
"previous": "xxx",
"next": "xxx"
}
}"
}
]
This response is from a batch call. If I call them separately, I can easily iterate through the responses, and get everything from them. When I call them in the batch though, I can't get past "body", and I need to use a batch call.
console.log(response[0].body); will return the object inside the body of the first part of the response, but console.log(response[0].body.data); returns undefined. I just don't get it. This should be simple but it's like there's a lock on the door and I don't have the right key.
I normally have no issue iterating through objects, so I don't need a generalized answer. I need help seeing whatever it is here that I don't see. Why does the console show undefined when I call anything after the body, and what do I need to be doing to get any of these values?
That JSON contains nested JSON. body seems to be a string. Use
var body = JSON.parse(response[0].body);
The values from the body are just strings.which are embedded as json.So firstly you would need to parse them using JSON.parse.
The code would be like
var body = JSON.parse(response[0].body);
A beginners question: I am trying to create and init an Array of users using the following string as initial data in JavaScript:
{ "user": {"notes": [{ "text": "Hello ", "date": "12\/1\/2013 5:01:36 AM", }], "name": "Alex"} }, { "user": { "notes": [{ "text": "Hi ", "date": "12\/1\/2013 5:15:19 PM"}, { "text": "It is me", "date": "12\/1\/2013 6:23:54 PM"}], "name": "Anna"} }
Is it possible in general (how?) or am I completely getting it wrong?
Your JSON is invalid. It contains a syntax error (possible a typo in the question) - an invalid comma after the first user's date, and it is also a list of objects that are not enclosed with the array syntax [].
The corrected json and example of parsing is:
Demo
var json = '[{ "user": {"notes": [{ "text": "Hello ", "date": "12\/1\/2013 5:01:36 AM" }], "name": "Alex"} }, { "user": { "notes": [{ "text": "Hi ", "date": "12\/1\/2013 5:15:19 PM"}, { "text": "It is me", "date": "12\/1\/2013 6:23:54 PM"}], "name": "Anna"} }]';
// ^ the list of objects need to be enclosed with []
var users = JSON.parse(json);
for(var i=0; i<users.length; i++)
{
console.log(users[i].user.name);
}
Generally speaking, you got that string using an ajax call, right?
and you can convert that string to an javascript object using JSON.parse(strToBeConverted)
in all modern browsers.
What if there is no such built-in JSON object? Do as below says,
1. import JS downloaded from this site which is created by Douglas Crockford,
2. use JSON.parse to do your business.
Make sure the JSON code is valid, use JSONLint for that. There is an error in your code, I fixed it in the code below.
Use JSON.parse() to transfer it to an object.
To be compatible to all browsers make sure you have json2 included as well (not all browsers have the JSON object to call the JSON.parse function).
As mentioned by Anthony the result is not an array but an object. To iterate over the user list see the jsfiddle or the example below.
EXAMPLE
var str = "[{user:...";
var userList = JSON.parse(str);
for(var i in userList){
var user = userList[i].user;
document.write(user.name + "<br/>");
}
CORRECTED JSON
[
{
\"user\": {
\"notes\": [
{
\"text\": \"Hello \",
\"date\": \"12/1/2013 5:01:36 AM\"
}
],
\"name\": \"Alex\"
}
},
{
\"user\": {
\"notes\": [
{
\"text\": \"Hi \",
\"date\": \"12/1/2013 5:15:19 PM\"
},
{
\"text\": \"It is me\",
\"date\": \"12/1/2013 6:23:54 PM\"
}
],
\"name\": \"Anna\"
}
}
]
I am trying to parse some json that my server replies me.
I am getting this answer from the server:
{
"ROWCOUNT": 1,
"COLUMNS": [
"REGISTRATION_DT",
"USERNAME",
"PASSWORD",
"FNAME",
"LNAME",
"EMAIL",
"MOBILE",
"FACEBOOK_ID"
],
"DATA": {
"REGISTRATION_DT": [
"March, 17 2012 16:18:00"
],
"USERNAME": [
"user"
],
"PASSWORD": [
pass
],
"FNAME": [
"name"
],
"LNAME": [
"lname"
],
"EMAIL": [
"somemail"
],
"MOBILE": [
mobile
],
"FACEBOOK_ID": [
"fbid"
]
}
}
I am trying to extract the data with this way:
var xml2 = this.responseData;
var xml3 = JSON.parse(xml2);
Ti.API.log(xml3.DATA[0].FNAME);
What I am doing wrong here?
You're reading your JSON wrong. DATA is an object of arrays and not vica versa.
Ti.API.log( xml3.DATA.FNAME[0] );
Ti.API.log(xml3.DATA.FNAME[0]);
Two fields come without quotes:
"PASSWORD": [
pass
]
And
"MOBILE": [
mobile
],
xml3.DATA is an object, not an array.
You need to write
xml3.DATA.FNAME[0]