how to parse this kind of json array - javascript

I have a json array like blew :
{
"0": {
"kind": "mammal",
"name": "Pussy the Cat",
"weight": "12kg",
"age": "5"
},
"1": {
"kind": "mammal",
"name": "Roxy the Dog",
"weight": "25kg",
"age": "8"
},
"2": {
"kind": "fish",
"name": "Piranha the Fish",
"weight": "1kg",
"age": "1"
},
"3": {
"kind": "bird",
"name": "Einstein the Parrot",
"weight": "0.5kg",
"age": "4"
}
}
i removed an element 'Piranha the Fish' With (UNSET) My json code changed to blow:
{
"0": {
"kind": "mammal",
"name": "Pussy the Cat",
"weight": "12kg",
"age": "5"
},
"1": {
"kind": "mammal",
"name": "Roxy the Dog",
"weight": "25kg",
"age": "8"
},
"3": {
"kind": "bird",
"name": "Einstein the Parrot",
"weight": "0.5kg",
"age": "4"
}
}
when I remove element the counter of the element change to 0,1,3
so now i can't to have full access in my json elements
I want echo value with this code :
for ($i = 0; $i < $JsonCount - 1; $i++) {
echo "Name :";
echo $json_cod[$i]['name'];
echo "<br/>";
echo "Age :";
echo $json_cod[$i]['age'];
echo "<br/>";
}
out put :
Name :Pussy the Cat
Age :5
Name :Roxy the Dog
Age :8

Try using foreach.
foreach ($json_cod as $item) {
echo "Name :";echo $item['name'];echo "<br/>";
echo "Age :";echo $item['age'];echo "<br/>";
}

If you want to use your code to echo ,after deleting a value from array use $newarray=array_values($oldarray) to reindex the array.

That is because unset() remove the value along with the key/index from the array and left it as it is,i.e it does not rearrange the key/index.
If you want to rearrange key the use array_slice() instead See array_slice. and you will get what you want. You will be able to do
for($i=0; $i <$JsonCount-1 ; $i++)
{
echo "Name :";echo $json_cod[$i]['name'];echo "<br/>";
echo "Age :";echo $json_cod[$i]['age'];echo "<br/>";
}

Related

Move next element/ recordset with interval javascript

If document.getElementById("countdowntimer").innerHTML is '0' then move to next recordset, i have set div class="area" with 100% height 100% with overflow hidden in html, body, i want show recordset one by one with interval time.
<?php
$mysqli = new mysqli("localhost", "root", "", "learningbydoing");
$result = mysqli_query($mysqli, "SELECT * FROM question");
while($record = mysqli_fetch_array($result)){
echo '<div class="area">
<div class="boxquestion">
<label>'.$record['no'].'</label><br>
<label>'.$record['question'].'</label><br>
<label id="countdowntimer">'.$record['time'].'</label><br>
</div></div>';
}?>
If you were to fetch the entire recordset using fetch_all() you could use that to generate a JSON variable which you could then process easily with Javascript using an interval / timer of some sort. For instance, your PHP might look like:
<?php
$db=new mysqli( 'localhost', 'root', '', 'learningbydoing' );
$results=$db->query( 'select * from question' )->fetch_all( MYSQLI_ASSOC );
$json=json_encode( $results );
printf('
<script>
const json=%s;
</script>',
$json
);
?>
The generated json ( the following is random sports from one of my databases to emulate possible data from your database. ) could then be used as in the following snippet. Try running the snippet...
const json = [{
"id": "70",
"question": "Beach Golf",
"time": "25"
},
{
"id": "81",
"question": "Belt Wrestling",
"time": "30"
},
{
"id": "421",
"question": "Lumberjack",
"time": "15"
},
{
"id": "144",
"question": "Chilean Rodeo",
"time": "10"
},
{
"id": "706",
"question": "Swamp Football",
"time": "40"
},
{
"id": "570",
"question": "Rollball",
"time": "1"
},
{
"id": "136",
"question": "Canopy Piloting",
"time": "9"
},
{
"id": "14",
"question": "Air Racing",
"time": "29"
},
{
"id": "402",
"question": "Kurash",
"time": "20"
},
{
"id": "465",
"question": "Northern Praying Mantis",
"time": "16"
},
{
"id": "53",
"question": "Ball Hockey",
"time": "3"
},
{
"id": "156",
"question": "Corkball",
"time": "13"
},
{
"id": "478",
"question": "Outrigger Canoeing",
"time": "7"
},
{
"id": "310",
"question": "Harness Racing",
"time": "9"
},
{
"id": "515",
"question": "Playboating",
"time": "8"
},
{
"id": "500",
"question": "Patball",
"time": "9"
},
{
"id": "202",
"question": "Dog Sledding",
"time": "14"
},
{
"id": "510",
"question": "Pigeon Racing",
"time": "16"
},
{
"id": "697",
"question": "Strongman",
"time": "18"
},
{
"id": "691",
"question": "Stock Car Racing",
"time": "19"
},
{
"id": "522",
"question": "Pommel Horse",
"time": "3"
},
{
"id": "237",
"question": "Field Hockey",
"time": "9"
},
{
"id": "312",
"question": "Heptathlon",
"time": "18"
},
{
"id": "324",
"question": "Horse Racing",
"time": "23"
},
{
"id": "7",
"question": "Aerobatics",
"time": "18"
}
];
const number = document.querySelector('i[data-name="number"]');
const question = document.querySelector('i[data-name="question"]');
const countdown = document.querySelector('i[data-name="countdown"]');
number.textContent = json[0].id;
question.textContent = json[0].question;
let _time = json[0].time;
(function(time) {
let t = NaN;
let i = 0;
(function() {
time--;
if (json[i]) {
countdown.textContent = time + 1;
number.textContent = json[i].id;
question.textContent = json[i].question;
}
t = setTimeout(arguments.callee, 1000);
if (time <= 0) {
if (i > Object.keys(json).length) {
clearTimeout(t);
number.textContent = '-';
question.textContent = 'Finished';
countdown.textContent = '-';
return false;
}
i++;
if (json[i]) time = json[i].time;
}
})();
})(_time);
[data-name] {
padding: 1rem;
margin: 1rem 0;
display: inline-block;
}
[data-name='number'] {
color: white;
background: green;
}
[data-name='question'] {
color: blue;
background: gold;
min-width: 15rem
}
[data-name='countdown'] {
color: white;
background: red;
}
<div class='area'>
<div class='boxquestion'>
<i data-name='number'></i>
<i data-name='question'></i>
<i data-name='countdown'></i>
</div>
</div>
example:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<style>
[data-name]{padding:1rem;margin:1rem 0;display:inline-block;}
[data-name='number']{color:white;background:green;}
[data-name='question']{color:blue;background:gold;min-width:15rem}
[data-name='countdown']{color:white;background:red;}
</style>
<?php
$db=new mysqli('localhost', 'root', '', 'learningbydoing');
$results=$db->query( 'select * from question' )->fetch_all( MYSQLI_ASSOC );
$json=json_encode( $results );
printf('
<script>
const json=%s;
</script>',
$json
);
?>
</head>
<body>
<div class='area'>
<div class='boxquestion'>
<i data-name='number'></i>
<i data-name='question'></i>
<i data-name='countdown'></i>
</div>
</div>
<script>
const number=document.querySelector('i[data-name="number"]');
const question=document.querySelector('i[data-name="question"]');
const countdown=document.querySelector('i[data-name="countdown"]');
number.textContent=json[0].id;
question.textContent=json[0].question;
let _time=json[0].time;
(function( time ){
let t=NaN;
let i=0;
(function(){
time--;
if( json[i] ){
countdown.textContent=time + 1;
number.textContent=json[i].id;
question.textContent=json[i].question;
}
t=setTimeout( arguments.callee, 1000 );
if( time <= 0 ){
if( i > Object.keys( json ).length ){
clearTimeout( t );
number.textContent='-';
question.textContent='Finished';
countdown.textContent='-';
return false;
}
i++;
if( json[ i ] ) time=json[ i ].time;
}
})();
})( _time );
</script>
</body>
</html>
<?php
$mysqli = new mysqli("localhost", "root", "", "learningbydoing");
$result = mysqli_query($mysqli, "SELECT * FROM question");
while($record = mysqli_fetch_array($result)){
if( $record['time'] > 0 ){ // assuming the column is actually a number
echo '<div class="area">
<div class="boxquestion">
<label>'.$record['no'].'</label><br>
<label>'.$record['question'].'</label><br>
<label id="countdowntimer">'.$record['time'].'</label><br>
</div></div>';
}
}?>

Decode json PHP find output only arrays containing POST string value

Im trying to make a simple JSON retriever.
So here is what im trying to do.
When i type for example
Japan. and i post the data to php.
I want it to load the json it has and search arrays for values containing this country Japan
Sending a smaller cut down json array containing only results containing this value back to the page.
The key is Country,
Example json
{
"1": {
"country": "America",
"Name": "Harry",
"Age": "41"
},
"2": {
"country": "America",
"Name": "ben",
"Age": "40"
},
"3": {
"country": "Japan",
"Name": "taka",
"Age": "48"
},
"4": {
"country": "Japan",
"Name": "John",
"Age": "41"
},
"5": {
"country": "America",
"Name": "Ted",
"Age": "41"
},
"6": {
"country": "America",
"Name": "Simon",
"Age": "41"
}
}
var country = $(".country").val();
$.ajax ({
url: json.php,
type: 'POST',
data: {
'find': country,
},
success: function (results) {
console.log(results);
},
fail: function(data) {
console.log( data.responseText );
console.log( 'Request Failed' + data.statusText );
}
})
<input name="country" class="country" type="text" placeholder="type country"></input>
<?php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
$jsonurl = "data.json";
$json = file_get_contents($jsonurl);
$find = $_POST["find"];
$decode = json_decode($json, true);
$results = array_filter($decode[''], function($country) {
return $country['country'] == $find;
});
var_dump($results);
Any help would be appreciated...
Here is the code sample using which you can achieve your requirement.
$my_json = '{
"1": {"country": "America","Name": "Harry","Age": "41"},
"2": {"country": "America","Name": "ben","Age": "40"},
"3": {"country": "Japan","Name": "taka","Age": "48"},
"4": {"country": "Japan","Name": "John","Age": "41"},
"5": {"country": "America","Name": "Ted","Age": "41"},
"6": {"country": "America","Name": "Simon","Age": "41"}
}';
$json_arr = json_decode($my_json);
$item = array();
foreach($j as $k=>$struct) {
if ('Japan' == $struct->country) {
$item[$k] = $struct;
}
}
echo 'Object Array form::';
echo '---------------------------';
print_r(array_values($item));
echo 'Json form::';
echo '---------------------------';
echo json_encode(array_values($item));

display remote value in from json associative array in JavaScript

How can I display the members.Rating for "Jones, Jim"? I have tried the syntax: echo members[$temp].Rating but it doesn't work.
let $temp = "Jones, Jim";
var members = [
{ "Rating": "1500", "Name": "Williams, Bill"},
{ "Rating": "2000", "Name": "Smith, Paul" },
{ "Rating": "1000", "Name": "Jones, Jim" },
{ "Rating": "1750", "Name": "Reynolds, Beverly" } ]
Use Array.find:
let $temp = "Jones, Jim";
var members = [
{ "Rating": "1500", "Name": "Williams, Bill"},
{ "Rating": "2000", "Name": "Smith, Paul" },
{ "Rating": "1000", "Name": "Jones, Jim" },
{ "Rating": "1750", "Name": "Reynolds, Beverly" } ]
console.log(
members.find(x => x.Name === $temp).Rating
)
You can't directly reference a member of an array by value, only by index.
So, you'll have to use the find method, like so:
const tempMember = members.find(p => p.Name === $temp)
const tempMemberRating= tempMember && tempMember.Rating
Note that if find doesn't find the element you want, it will return undefined. This makes the mult-line approach necessary, as simply calling it all in one line could result in a TypeError. e.g.:
members.find(p => p.Name === "Johnson, Jimmy").Rating
Since find returns undefined here, you're attempting to reference undefined.Rating, which will throw an error.
Try this:
For (var i=0 ;i <members.length ;i++){
If ( members[i].Name == $temp ){
console.log (members[i].Raiting);
}
}

Create JSON object with same keys for API call

I'm trying to create a JSON object for an API call which has the following format:
....
"Key": "Value",
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "20",
"Width": "25",
"Height": "30"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "80"
}
},
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "15",
"Width": "24",
"Height": "27"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "50"
}
},
"Key": "Value",
....
I should add as many "Package" objects as needed. However, I've tried doing this in many different ways but every time that I parse the variable to be used the first objects get overwritten and I end up with only the last object.
This is what I'm trying at the moment, still with no luck:
var lineItems = '{';
for (var i=0;i<inputObject.packages.length;i++) {
lineItems += '"Package": {"PackagingType": {"Code": "02","Description": "Rate"},"Dimensions": {"UnitOfMeasurement": {"Code": "IN","Description": "inches"},"Length": ' + inputObject.packages[i][0].toString() + ',"Width": ' + inputObject.packages[i][1].toString() + ',"Height": ' + inputObject.packages[i][2].toString() + '},"PackageWeight": {"UnitOfMeasurement": {"Code": "Lbs","Description": "pounds"},"Weight": ' + inputObject.packages[i][3].toString() + '}}';
if (i !== inputObject.packages.length-1) {
lineItems += ',';
}
}
lineItems += '}';
lineItems = JSON.parse(lineItems);
How about numbering your packages, ie:
for (var i=0;i<inputObject.packages.length;i++) {
lineItems+='"Package" + i : { ... }'
}
edit: to get required result (as an array - because it's not JSON), here's an example:
var a=[];
var b={"package": {"c":100,"d":200,"e":300}}
var c={"package": {"c":800,"d":700,"e":600}}
a.push(b);
a.push(c);
console.log(a);

Javascript | JSON and ARRAY

May be you can help me with my task. I have a JSON string:
{
"chats":[
{"id":"1","time":"13:02", "from_id":"2692","text":"1","to_id":"62"},
{"id":"2","time":"13:48", "from_id":"62","text":"Hello!","to_id":"2692"},
{"id":"12","time":"15:47", "from_id":"2692","text":"3","to_id":"62"},
{"id":"13","time":"15:48", "from_id":"62","text":"4","to_id":"2692"},
{"id":"30","time":"08:57", "from_id":"2692","text":"To me","to_id":"62"},
{"id":"31","time":"09:28", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"2692","text":"From user1","to_id":"66"}
],
"lastid": "32"
}
var my_id = 2692 /*My chats*/
/*Success JSON request below*/
onSuccess: function(m){
var messages = [];
var chanels = [];
var chanels_u = [];
for(var i=0; i<m.chats.length;i++){
if (my_id != '' && m.chats[i].from_id != parseInt(my_id)){
chanels.push(m.chats[i].from_id);
}
}
chanels_u = chanels.unique(); /*We get id's: 62,66*/
}
My Question:
How can I create a new arrays dynamically (2 for this example for: 62 and 66) and push messages?
To 1 (62):
{"id":"1","time":"13:02", "from_id":"2692","text":"1","to_id":"62"},
{"id":"2","time":"13:48", "from_id":"62","text":"Hello!","to_id":"2692"},
{"id":"12","time":"15:47", "from_id":"2692","text":"3","to_id":"62"},
{"id":"13","time":"15:48", "from_id":"62","text":"4","to_id":"2692"},
{"id":"30","time":"08:57", "from_id":"2692","text":"To me","to_id":"62"}
To 2 (66):
{"id":"31","time":"09:28", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"2692","text":"From user1","to_id":"66"}
Thanks!
You are already identifying your chat ID and pushing it into the chanels array in your code:
if (my_id != '' && m.chats[i].from_id != parseInt(my_id)){
chanels.push(m.chats[i].from_id);
}
You are also identifying unique IDs in your code:
chanels_u = chanels.unique();
All you need to do is locate your chats from the JSON object by comparing them to the IDs in chanels_u and if there's a match, push the text field to the messages array. This is should be close to what you require:
for(var i=0; i<m.chats.length;i++){
for(var j=0; j<chanels_u.length;j++){
if (my_id !== '' && m.chats[i].from_id === chanels_u[j]){
messages.push(m.chats[i].text);
}
}
}
this will do what you want, i believe - create a new object with keys of the to_id and from_id in a way that allows you to loop them whichever way you want. it would probably make more sense to have a toUser and fromUser objects that you can loop independently and cross reference as you build the replies but it's trivial to do so.
var chats = {
"chats":[
{"id":"1","time":"13:02", "from_id":"2692","text":"1","to_id":"62"},
{"id":"2","time":"13:48", "from_id":"62","text":"Hello!","to_id":"2692"},
{"id":"12","time":"15:47", "from_id":"2692","text":"3","to_id":"62"},
{"id":"13","time":"15:48", "from_id":"62","text":"4","to_id":"2692"},
{"id":"30","time":"08:57", "from_id":"2692","text":"To me","to_id":"62"},
{"id":"31","time":"09:28", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"2692","text":"From user1","to_id":"66"}
],
"lastid": "32"
};
var newchats = {}, my_id = 2692;
chats.chats.each(function(chat) {
if (!chat.id || !chat.id.length || chat.from_id == my_id)
return;
newchats["from" + chat.from_id] = newchats["from" + chat.from_id] || [];
newchats["from" + chat.from_id].push(chat);
newchats["to" + chat.to_id] = newchats["to" + chat.to_id] || [];
newchats["to" + chat.to_id].push(chat);
});
console.log(newchats, JSON.encode(newchats));
see on jsfiddle http://jsfiddle.net/dimitar/7j2SN/, outputs:
{
"from62": [{
"id": "2",
"time": "13:48",
"from_id": "62",
"text": "Hello!",
"to_id": "2692"},
{
"id": "13",
"time": "15:48",
"from_id": "62",
"text": "4",
"to_id": "2692"}],
"to2692": [{
"id": "2",
"time": "13:48",
"from_id": "62",
"text": "Hello!",
"to_id": "2692"},
{
"id": "13",
"time": "15:48",
"from_id": "62",
"text": "4",
"to_id": "2692"},
{
"id": "31",
"time": "09:28",
"from_id": "66",
"text": "From user1",
"to_id": "2692"},
{
"id": "32",
"time": "09:29",
"from_id": "66",
"text": "From user1",
"to_id": "2692"}],
"from66": [{
"id": "31",
"time": "09:28",
"from_id": "66",
"text": "From user1",
"to_id": "2692"},
{
"id": "32",
"time": "09:29",
"from_id": "66",
"text": "From user1",
"to_id": "2692"}]
}
I guess, JSON is invalid. You missed to close the JSON properly.
{
"chats": [
{
"id": "1",
"time": "13:02",
"from_id": "2692",
"text": "1",
"to_id": "62"
},
{
"id": "2",
"time": "13:48",
"from_id": "62",
"text": "Hello!",
"to_id": "2692"
},
{
"id": "12",
"time": "15:47",
"from_id": "2692",
"text": "3",
"to_id": "62"
},
{
"id": "13",
"time": "15:48",
"from_id": "62",
"text": "4",
"to_id": "2692"
},
{
"id": "30",
"time": "08:57",
"from_id": "2692",
"text": "To me",
"to_id": "62"
},
{
"id": "31",
"time": "09:28",
"from_id": "66",
"text": "From user1",
"to_id": "2692"
},
{
"id": "32",
"time": "09:29",
"from_id": "66",
"text": "From user1",
"to_id": "2692"
}
]
}
Use JSONLINT to validate your data. You can update(get/set) this array dynamically as you wish.
var msgBox={"chats":[]};
var msg={"id":1,"time":(new Date()).getTime(),"from_id":"","text":"","to_id":""};
var info={ // whole JSON data }
var chats=info['chats'];
for(m in chats){
console.log(chats[m].text) // will display the text
console.log(chats[m].time) // will display the time of chat
chat[m].to_id=32424; // you can modify the to_id value
}
You can make chanels and object instead of array.
onSuccess: function(m){
var messages = [];
var chanels = {};
var chanels_u = [];
for(var i=0; i<m.chats.length;i++){
if (my_id != '' && m.chats[i].from_id != parseInt(my_id)){
var fromID = m.chats[i].from_id;
if(!chanels[fromID]){
chanels[fromID] = [];
}
chanels[fromID].push(m.chats[i]);
}
}
//chanels_u = chanels.unique(); /*We get id's: 62,66*/
}

Categories