I've a php query which creates the JSON data of the the data received from the SQL query that is run. The JSON data is created using this query using this query
echo json_encode($res->fetch_all(MYSQLI_ASSOC), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT );
Now I want to plot a chart using fusionchart for which I need to convert this data into an array. I tried a sample JS code to convert the JSON data into an JS array and it worked
var data = { "timestamp": "2016-09-23", "value1": "0", "value2": "0", ........., "value49": "0", "value50": "0" };
var arr = [];
for (elem in data) {
arr.push(data[elem]);
}
console.log(arr);
Now in the data variable I need to pass the data from php code. This is just one of the records that I entered manually. There are over a million records and I need to convert all of them. How I do this?
You can use parseJSON() function :
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
You can just use Object.values() function to acquire values from an object.
var data = { "timestamp": "2016-09-23", "value1": "0", "value2": "0", "value49": "0", "value50": "0" };
var arr = Object.values(data);
console.log(arr);
For PHP
You can send only values and omit keys in PHP using following code. json_decode converts JSON string to an array. implode converts an array to a string.
<?php
$str = '{ "timestamp": "2016-09-23", "value1": "val1",
"value2": "val2", "value49": "val49", "value50": "val50" }';
$myJSON = json_decode($str, true);
echo '[' . implode(",", $myJSON) . ']';
Results:
[2016-09-23,val1,val2,val49,val50]
Related
I am reading a local csv file with ajax query , and then loading read values into an array.
This is how the string value looks like in the csv file :
"Tiger","Architect","800","DRP","5421","VFX"
after loading this string into the array , the array looks like this :
0: (6) ["Tiger", "Architect", "800", "DRP", "5421", "VFX"]
now I am trying to convert this above mentioned sting into a json object to look like this :
{
"data": [
{
"0": "Tiger",
"1": "Architect",
"2": "800",
"3": "DRP",
"4": "5421",
"5": "VFX"
}]
}
by having all the values inside one object data
I tried this :
var arrayToString = JSON.stringify(Object.assign({}, data1));
var stringToJsonObject = JSON.parse (arrayToString) ;
it converts the array to json, but with length 6 where as I need the length to be 1
any way to do this ?
I think you have almost done everything, when you create object - just wrap array in []
const arr = ["Tiger", "Architect", "800", "DRP", "5421", "VFX"];
var arrayToString = JSON.stringify(Object.assign({}, [arr]));
var stringToJsonObject = JSON.parse (arrayToString) ;
console.log(stringToJsonObject);
You can do this using Object.entries and Object.fromEntries.
const arr = ["Tiger", "Architect", "800", "DRP", "5421", "VFX"];
const result = {data: []};
result.data.push(Object.fromEntries(Object.entries(arr)));
console.log(result);
In practice, I create an array in PHP that then I pass to a JavaScript function.
So far so good. The array that the functions recieves is the following:
[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]
My problem is to get all the first array, that is this: {"firstname": "Micheal", "lastname": "Brown"}
and also the second array this: {"car": "Ford", "model": "Fiesta"}
I tried with alert (array [0]) but it only shows me this [
How can I do this?
I'll explain:
this is my php file:
class UserClasses
{
public $firstname;
public $lastname;
}
class CarClasses
{
public $car;
public $model;
}
if(isset($_POST['name'])){
populate($_POST['name']);
}
function populate(){
//I abbreviated the function for simplicity
$arrayUser = array();
$arrayCar = array();
$user = new UserClasses();
$user->firstname = "Micheal";
$user->lastname = "Brown";
array_push($arrayUser, $user);
$car = new CarClasses();
$car->car = "Ford";
$car->model = "Fiesta";
array_push($arrayCar, $car);
$arrayFinal = array($arrayUser, $arrayCar);
print json_encode($arrayFinal);
}
and this is the function in javascript:
//Ajax for calling php function
$.post('Classes.php', { name: name }, function(data){
var array = JSON.parse(data);
var arrayT = array[0];
alert(arrayT);
});
Here's what is happening with your code: you're accessing the first element of a JSON string, so my guess is you will get its first character: [.
You need to convert your string into an actual array before accessing it!
Use JSON.parse:
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
- MDN web docs
For example you can do:
const json = '[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]'
// that's what you have
console.log(json[0])
// that's what you want
array = JSON.parse(json)
console.log(array[0])
First of all, if you are using json_encode to pass PHP array to JS, it encodes it to a JSON string. You have to parse it using JSON.parse() and only then the json string is transformed to regular array which you can use.
You can parse data and use it:
var arr = '<?php echo '[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]'; ?>';
var parsedarr = JSON.parse(arr);
for(var i=0;i<parsedarr.length;i++){
console.log(parsedarr[i][0]);
}
You are dealing with 3 different Data Types:
a PHP Multidimensional Array
a JSON String
a Javascript Object
Each needs to be converted into the next.
A PHP Array is converted into a JSON String, via json_encode() (in PHP)
A JSON String is converted into a Javascript Object, via JSON.parse() (in Javascript)
Now you have a Javascript Object which you can interrogate and manipulate using Javascript.
PHP Multidimensional Array:
$My_PHP_Array = array(
array(
'firstname' => 'Michael'
'lastname' => 'Brown'
),
array(
'car' => 'Ford'
'model' => 'Fiesta'
)
);
Convert PHP Multidimensional Array to JSON String:
json_encode($My_PHP_Array);
JSON String:
'{
[
[{
"firstname": "Micheal",
"lastname": "Brown"
}],
[{
"car": "Ford",
"model": "Fiesta"
}]
]
}'
Convert JSON String to Javascript Object:
var myJavascriptObject = JSON.parse(myJSONString);
Javascript Object:
myJavascriptObject = {
[
[{
"firstname": "Micheal",
"lastname": "Brown"
}],
[{
"car": "Ford",
"model": "Fiesta"
}]
]
};
I want to convert the following string to an array
[{id: "1", type: "railroadCrossingSign", latitude: "55.647432", longtitude: "12.187673"}, {id: "2", type: "stationSign", latitude: "55.647444", longtitude: "12.187545"}]
Unfortunately an error occurs when I am JSON.parse(), probably because of the objects in the string...
How do i convert a JSON string with objects to an array with objects?
JSON format requires that your keys also must be wrapped into "".
var string = '[{"id": "1", "type": "railroadCrossingSign", "latitude": "55.647432", "longtitude": "12.187673"}, {"id": "2", "type": "stationSign", "latitude": "55.647444", "longtitude": "12.187545"}]';
var arr = JSON.parse(string);
console.log(arr);
In order to achieve what you want. Your JSON key value pair must in a string format too.
Say,
var obj = '[{
"key" : "value"
}]';
Finally, when you use:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
You get the following results:
John, 30
Some observations :
First make sure your JSON should be a valid JSON.
Object properties should be wrapped into quotes "".
If your JSON is already an JSON Object then no need to parse it again otherwise it will throw an error.
var jsonObj = [{
"id": "1",
"type": "railroadCrossingSign",
"latitude": "55.647432",
"longtitude": "12.187673"
}, {
"id": "2",
"type": "stationSign",
"latitude": "55.647444",
"longtitude": "12.187545"
}];
var newObj = JSON.parse(jsonObj);
console.log(newObj); // Error : Uncaught SyntaxError: Unexpected token o in JSON at position 1
I've json in this format :
[
{
"_id": {
"$oid": "560c079e1691682b4ff327ad"
},
"year": "2015",
"month": "9",
"day": "30",
"time": "17:02:17",
"problemDesc": "test",
"resolution": "test",
"IM": "test"
}
]
I'm attempting to access the year using : console.log(json[0].year) but receiving undefined. How to access the year value from this json string ?
fiddle :
http://jsfiddle.net/b8dggkof/
In the JSFiddle the value inside json is a string and not a JavaScript Object, you have to parse the string before try to access the value:
var json = JSON.parse('{"":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}');
console.log(json[''][0].year);
After you parsed the string, you need to access the object with key an empty string:
json['']
The value associated to this key is an array and you need the first element, so:
json[''][0]
Now you can get the year:
json[''][0].year
You need to put in a key for the JSON and then access by the key the inner Object, after you parse it since it is a string enclosed in quotes '
var json = '{"key":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}'
console.log(JSON.parse(json)['key'][0].year);
you need to parse you json string to json object by using JSON.parse then use key name in you case which is ''(empty string)
var jsonStr = '{"":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}';
var parseJson = JSON.parse(jsonStr);
alert(parseJson[''][0].year)
I am using twitterapi to get the friends list in php and I have encoded the result as a json array, but I cannot parse the json array in javascript.I have validated the json array produced by the php and its a valid json array. Below is my code.
php
$friends = array();
$friend_list = array();
$myfriend = array();
$connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET,oauth_token,oauth_token_secret);
$friends =$connection->get("https://api.twitter.com/1.1/friends/list.json?cursor=-1&screen_name=twitterapi&skip_status=true&include_user_entities=false&count=200);
foreach($friends as $friend) {
if(!empty($friend))
{
foreach($friend as $value)
{
$friend_list['id']=$value->id;
$friend_list['screen_name']= $value->screen_name;
$friend_list['name']= $value->name;
$friend_list['profile_image_url']= $value->profile_image_url;
$friend_list['location']= $value->location;
array_push($myfriend, $friend_list);
}
}
}
$newarray = json_encode($myfriend);
'
javascript
<script>
var obj1 = JSON.parse('<?php echo $newarray ;?>');
console.log(obj1); // am not getting anything in console
</script>
EDITED
output from echo $newarray;
[
{
"id": 50393960,
"screen_name": "BillGates",
"name": "Bill Gates",
"profile_image_url": "http://pbs.twimg.com/profile_images/1884069342/BGtwitter_normal.JPG",
"location": "Seattle, WA"
},
{
"id": 141527741,
"screen_name": "prakashraaj",
"name": "Prakash Raj",
"profile_image_url": "http://pbs.twimg.com/profile_images/2951815972/ab32fb806b480d0dc761805ae4ef9775_normal.jpeg",
"location": "india"
},
{
"id": 88856792,
"screen_name": "aamir_khan",
"name": "Aamir Khan",
"profile_image_url": "http://pbs.twimg.com/profile_images/2254031972/_MG_2190_normal.jpeg",
"location": "Mumbai"
},
{
"id": 107318424,
"screen_name": "bipsluvurself",
"name": "Bipasha Basu",
"profile_image_url": "http://pbs.twimg.com/profile_images/419745345178832896/8JvqwEM9_normal.jpeg",
"location": "Mumbai, India"
}
]
Please help, am stuck with this
You can directly output the json:
Change to:
var obj1 = <?php echo $newarray ;?>;
For example:
<?php
$newarray = json_encode(array('name' => 'srain'));
?>
var obj1 = <?php echo $newarray ;?>;
It will output:
var obj1 = {"name":"srain"};
update
If your js script is not in the same file with the php code, the $newarray will be null.
In the absence of information about how you validated json array, this is what I can recommend. Change your javascript to:
<script>
var jsonString = '<?php echo $newarray ;?>';
console.log(jsonString);
var obj1 = JSON.parse(jsonString);
console.log(obj1); // am not getting anything in console
</script>
You can see the content of jsonString in the javascript console. That should give you hints about what is going wrong.
Note:You are fetching JSON content from twitter, converting it to PHP data structure and converting it back to JSON. Sending the JSON string from twitter to javascript is far more efficient - if there is no need to filter/alter the twitter returned data.