javascript / jquery Accessing JSON array by both name and index - php

I am very much hoping you can help me with this as I've spent all too much time on this. First, my JSON formatting is unfortunately not very mutable and I have moved it to a number of different formats to support both some jquery and a php-based search. Each time I move it, the search will work and the rest of the site will break or vice-versa.
Is it possible to access a JSON array by both name and index number? Here is my JSON (stored in PHP file and being retrieved & converted successfully to valid JSON):
<?php
$contents = array(
'Song Name #1 by Artist Name #1 (maininfo)' => array(
'contentid' => '1',
'aname' => 'Artist Name',
'sname' => 'Song Name',
'main' => 'core content #1',
'maininfo' => 'url')
),
'Song Name #2 by Artist Name #2 (maininfo)' => array(
'contentid' => '2',
'aname' => 'Artist Name',
'sname' => 'Song Name',
'main' => 'core content #2',
'maininfo' => 'url')
);
?>
My search works when something in the array title is matched on, otherwise it returns no matches so I must leave the array title as-is.
Another part of my project uses jquery and has the following:
parse(jsonobj[0][1]['sname']) //successfully already returning 'Song Name'
The above will ONLY work when the array title is not provided (e.g. 'Song Name #1 by Artist Name #1 (maininfo)' => array( becomes simply array(.
For those curious, file is being converted to JSON using:
var jsonobj;
$.ajax({
url: 'getjson.php',
dataType: "json",
success: function (doc) {
jsonobj = doc;
}
});
On the PHP side, when getjson.php is called the JSON array (above) is loaded in and converted to valid JSON using:
$final = array($final_contents);
header('Content-type: application/json');
echo json_encode($final);
Note: $final_contents is just $contents with an additional header added. See Searching JSON array for values and accessing surrounding keys/values; output as JSON for the PHP I have running specifically.
Thank you in advance.

JavaScript does not support arrays with named indexes. You should encode it as a JSON object instead.
var $contents = {
"Song Name #1 by Artist Name #1 (maininfo)": {
"contentid": 1,
"aname": "Artist Name",
"sname": "Song Name",
"main": "core content #1",
"maininfo": "url"
},{
"Song Name #2 by Artist Name #2 (maininfo)": {
"contentid": 2,
"aname": "Artist Name",
"sname": "Song Name",
"main": "core content #2",
"maininfo": "url"
}
};
Although it would probably be better to arrange it this way (here's a fiddle to demonstrate:
var songs = [
{
"contentid": 1,
"artist": "Artist Name",
"title": "Song Title 1",
"main": "core content #1",
"maininfo": "url"
},
{
"contentid": 2,
"artist": "Artist Name",
"title": "Song Title 2",
"main": "core content #2",
"maininfo": "url"
}
];
Then you can search through your songs list by id, or iterate through to filter on specific field values. For instance to find all songs whose titles start with "Song Title":
var findAllSongs = function(prop, value){
var result = new Array();
for (var i = 0; i < songs.length; i++) {
var song = songs[i];
if (song[prop] && (song[prop] === value || song[prop].search(value) >= 0)){
result.push(song);
}
}
return result;
};
var song = findAllSongs("title","Song Title 2")[0];
alert(song.contentid);
// Outputs "2"
The php equivalent of my json above is:
$songs = array(
array(
"contentid" => 1,
"artist" => "Artist Name",
"title" => "Song Title 1",
"main" => "core content #1",
"maininfo" => "url",
),
array(
"contentid" => 2,
"artist" => "Artist Name",
"title" => "Song Title 2",
"main" => "core content #2",
"maininfo" => "url",
)
);
If you're using PHP 5.4 or higher, you can use the short syntax:
$songs = [
[
"contentid" => 1,
"artist" => "Artist Name",
"title" => "Song Title 1",
"main" => "core content #1",
"maininfo" => "url",
],[
"contentid" => 2,
"artist" => "Artist Name",
"title" => "Song Title 2",
"main" => "core content #2",
"maininfo" => "url",
]
];
Then you can turn it into JSON by using your current method:
json_encode($songs);

You are having array. convert it to json using following code (json_encode) and echo so that jquery can receive it:
$jsonVar = json_encode($contents);
echo $jsonVar;
Update:
Code to call json using ajax is:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Alternatively you can use shorthand for it:
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Of course the file being sent should be in json format, that is:
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
for that you need to convert the array into json.

Related

How to refer JSON used with PHP and stored the surveyjs in mysql

My php file has code look like this
<?php
$connect = mysqli_connect("localhost","root","","surveytest");
$query = '';
$table_data = '';
$filename2 = "employee_data.js";
$data2 = file_get_contents($filename2);
$array2 = json_decode($data2, true);
foreach($array2 as $row) //Extract the Array Values by using Foreach Loop
{
$query .= "INSERT INTO survey(name, gender, designation)
VALUES
('".$row["name"]."',
'".$row["gender"]."',
'".$row["designation"]."'); "; // Make Multiple Insert Query
$table_data .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["gender"].'</td>
<td>'.$row["designation"].'</td>
</tr>
'; //Data for display on Web page
}
if(mysqli_multi_query($connect, $query)) //Run Mutliple Insert Query
{
echo '<h3>Imported JSON Data</h3><br />';
echo '
<table class="table table-bordered">
<tr>
<th width="45%">Name</th>
<th width="10%">Gender</th>
<th width="45%">Designation</th>
</tr>
';
echo $table_data;
echo '</table>';
}
?>
My javascript file has code look like this
var json =
{
"items": [
{
"name": "Rusydi",
"gender": "Male",
"designation": "System Architect"
},
{
"name": "Hakim",
"gender": "Male",
"designation": "Conservation worker"
}
]
}
Hey! i am a beginner for javascript and JSON.
I try to add var json into mysql database.
Now i want to refer to this javascriptfile(var json) but it's don't work.
My purpose is try to stored this variable in mysql.
That's why i try to do like this.
var json = {
questions: [
{
name: "name",
type: "text",
title: "Please enter your name:",
placeHolder: "Jon Snow",
isRequired: true
}, {
name: "birthdate",
type: "text",
inputType: "date",
title: "Your birthdate:",
isRequired: true
}, {
name: "color",
type: "text",
inputType: "color",
title: "Your favorite color:"
}, {
name: "email",
type: "text",
inputType: "email",
title: "Your e-mail:",
placeHolder: "jon.snow#nightwatch.org",
isRequired: true,
validators: [
{
type: "email"
}
]
}
]
};
This is full code.
https://surveyjs.io/Examples/Library/?id=questiontype-text&platform=jQuery&theme=default
Survey
.StylesManager
.applyTheme("default");
var json = {
questions: [
{
name: "name",
type: "text",
title: "Please enter your name:",
placeHolder: "Jon Snow",
isRequired: true
}, {
name: "birthdate",
type: "text",
inputType: "date",
title: "Your birthdate:",
isRequired: true
}, {
name: "color",
type: "text",
inputType: "color",
title: "Your favorite color:"
}, {
name: "email",
type: "text",
inputType: "email",
title: "Your e-mail:",
placeHolder: "jon.snow#nightwatch.org",
isRequired: true,
validators: [
{
type: "email"
}
]
}
]
};
window.survey = new Survey.Model(json);
survey
.onComplete
.add(function (result) {
document
.querySelector('#surveyResult')
.innerHTML = "result: " + JSON.stringify(result.data);
});
$("#surveyElement").Survey({model: survey});
or what should i do?
Remove the "var json =" from your file and change the extension to ".json" instead of ".js".
Since your javascript file does not contain a valid JSON string it cannot be decoded by php.
employee_data.json
{
"items": [
{
"name": "Rusydi",
"gender": "Male",
"designation": "System Architect"
},
{
"name": "Hakim",
"gender": "Male",
"designation": "Conservation worker"
}
]
}
Ok the problem as I see it is this:
//employee_data.js
var json =
{
And then you import that
$filename2 = "employee_data.js";
$data2 = file_get_contents($filename2);
$array2 = json_decode($data2, true);
JSON is not JavaScript code (strictly speaking), it's way to format or encode JavaScript objects as strings. (JavaScript Object Notation). So your file should start with { and not a variable setting. So you just need to remove that var json = bit.
If you check var_dump($array2); it will probably say NULL and if you check echo json_last_error_msg() right after doing json_decode it will probably say something like Syntax error invalid JSON etc..
This can be reproduced like this:
var_dump(json_decode('var json={"foo":"bar"}', true));
echo json_last_error_msg();
Output:
NULL
Syntax error
Sandbox
If you remove the var json = from my overly simple example, you get this:
array(1) {
["foo"]=> string(3) "bar"
}
No error
Cheers!
First, isolate the json data which immediately follows var json = and ends with } which is followed immediately by ;.
Then repair the json string by wrapping all of the keys in double quotes.
Finally, convert the data to an array so that you can perform your query process with the questions subarrays.
*Note, I DO NOT recommend that you use mysqli_multi_query() because it is unstable/insecure. I recommend that you use a prepared statement to INSERT your data. I will refrain from explaining this task because there are many, many examples of how to do this on StackOverflow.
Code: (PHP Demo) (Regex 1 Demo) (Regex 2 Demo)
if (preg_match('~^var json = \K{.*?}(?=;)~ms', $js_file_contents, $match)) { // cut away extra
$json = preg_replace('~^\s*\K\w+~m', '"\0"', $match[0]); // quote-wrap the keys
var_export(json_decode($json, true)); // convert json string to array and display
}
Output:
array (
'questions' =>
array (
0 =>
array (
'name' => 'name',
'type' => 'text',
'title' => 'Please enter your name:',
'placeHolder' => 'Jon Snow',
'isRequired' => true,
),
1 =>
array (
'name' => 'birthdate',
'type' => 'text',
'inputType' => 'date',
'title' => 'Your birthdate:',
'isRequired' => true,
),
2 =>
array (
'name' => 'color',
'type' => 'text',
'inputType' => 'color',
'title' => 'Your favorite color:',
),
3 =>
array (
'name' => 'email',
'type' => 'text',
'inputType' => 'email',
'title' => 'Your e-mail:',
'placeHolder' => 'jon.snow#nightwatch.org',
'isRequired' => true,
'validators' =>
array (
0 =>
array (
'type' => 'email',
),
),
),
),
)

Mustache.php rendering multi-dimensional data

I'm utilizing Mustache to template some XML responses for an API. I was wondering how I could use the XML template below to render data from this array?
The data is not rendering at all when using this code:
$result = $m->render($template, $r);
echo $result;
Here is JSON converted data:
[
{
"UUID": "655482ab-38ee-433f-b310-1f6f227113b9",
"RefUUID": "92a8ecf6-8eb6-4d1e-b88d-59b50c3b0cc9",
"company":"UAR",
"itemname":"DOOR ",
"daysinstock":"41",
"condition":"A",
"stocknumber":"F0049356",
"ic":"120-00409AL",
"price":"750.00",
"quantity":"1",
"location":"U3020",
"comments": "comment for #0"
},
{
"UUID": "655482ab-38ee-433f-b310-1f6f227113b9",
"RefUUID": "92a8ecf6-8eb6-4d1e-b88d-59b50c3b0cc9",
"company":"UAR",
"itemname":"DOOR ",
"daysinstock":"68",
"condition":"C",
"stocknumber":"F0048586",
"ic":"120-00409AL",
"price":"750.00",
"quantity":"1",
"location":"KEEP"
"comments": "comment for #1"
},
{
"UUID": "655482ab-38ee-433f-b310-1f6f227113b9",
"RefUUID": "92a8ecf6-8eb6-4d1e-b88d-59b50c3b0cc9",
"company":"UAR",
"itemname":"DOOR ",
"daysinstock":"280",
"condition":"B",
"stocknumber":"171013",
"ic":"120-00409AL",
"price":"750.00",
"quantity":"1",
"location":"YCR4"
"comments": "comment for #2"
}
]
XML template trying to render
$template = '<SupplierResponse>
<QuotedPartList>
{{#parts}}
<QuotedPart>
<BMSObject>
<UUID>{{UUID}}</UUID>
<RefUUID>{{RefUUID}}</RefUUID>
</BMSObject>
<SupplierResponseCode>AsRequested</SupplierResponseCode>
<SupplierRefLineNum>{{SupplierRefLineNum}}</SupplierRefLineNum>
<PartNumInfo>
<PartNumType>Stock</PartNumType>
<PartNum>{{stocknumber}}</PartNum>
</PartNumInfo>
<PartNumInfo>
<PartNumType>IC</PartNumType>
<PartNum>{{ic}}</PartNum>
</PartNumInfo>
<PartType>PAL</PartType>
<PartDesc>{{itemname}}</PartDesc>
<PriceInfo>
<UnitListPrice>{{price}}</UnitListPrice>
<UnitNetPrice>{{price}}</UnitNetPrice>
</PriceInfo>
<RInfo>
<Grade>{{condition}}</Grade>
<DaysInStock>{{daysinstock}}</DaysInStock>
<PartLocation>{{location}}</PartLocation>
<PartStore>{{company}}</PartStore>
</RInfo>
<Availability>
<Quantity>{{quantity}}</Quantity>
<InventoryStatus>Available</InventoryStatus>
<AvailableShipDate>2018-05-10</AvailableShipDate>
</Availability>
<LineNoteInfo>
<LineNoteMemo>{{comments}}</LineNoteMemo>
</LineNoteInfo>
</QuotedPart>
{{/parts}}
</QuotedPartList>
</SupplierResponse>';
Edit: Based on new information that came to light after I posted this answer - your issue occurred because Mustache requires data to be stored in an associative array.
// Not correct
$data = [
[
'Foo' => 'Bar'
],
[
'Biz' => 'Buz'
],
]
// Correct
$data = [
'MyData' => [
[
'Foo' => 'Bar'
],
[
'Biz' => 'Buz'
]
]
]
You could try something like this:
<?php
$objectToPassIn = [
'parts' => [
// .. your data here
]
];
// Load template and initialize Mustache
$m = new Mustache_Engine(array(
'loader' => new Mustache_Loader_FilesystemLoader('path/to/where/template/is/stored', array('extension' => '.xml'))
));
$rendered = $m->render(
'template-name-without-file-extension',
$objectToPassIn
);
Finally got it fixed. The data was not formatted correctly:
Data:
$r = array("parts"=> array(
"UUID"=> "655482ab-38ee-433f-b310-1f6f227113b9",
"RefUUID"=> "92a8ecf6-8eb6-4d1e-b88d-59b50c3b0cc9",
"company"=>"UAR",
"itemname"=>"DOOR ",
"daysinstock"=>"41",
"condition"=>"A",
"stocknumber"=>"F0049356",
"ic"=>"120-00409AL",
"price"=>"750.00",
"quantity"=>"1",
"location"=>"U3020",
"comments"=> "comment for #0",
"SupplierRefNum"=> 1
),
array(
"UUID"=> "655482ab-38ee-433f-b310-1f6f227113b9",
"RefUUID"=> "92a8ecf6-8eb6-4d1e-b88d-59b50c3b0cc9",
"company"=>"UAR",
"itemname"=>"DOOR ",
"daysinstock"=>"68",
"condition"=>"C",
"stocknumber"=>"F0048586",
"ic"=>"120-00409AL",
"price"=>"750.00",
"quantity"=>"1",
"location"=>"KEEP",
"comments"=> "comment for #1",
"SupplierRefNum"=> 2
),
array(
"UUID"=> "655482ab-38ee-433f-b310-1f6f227113b9",
"RefUUID"=> "92a8ecf6-8eb6-4d1e-b88d-59b50c3b0cc9",
"company"=>"UAR",
"itemname"=>"DOOR ",
"daysinstock"=>"280",
"condition"=>"B",
"stocknumber"=>"171013",
"ic"=>"120-00409AL",
"price"=>"750.00",
"quantity"=>"1",
"location"=>"YCR4",
"comments"=> "comment for #2",
"SupplierRefNum"=> 3
}
}
);
Code:
$result = $m->render($template, $r); // Used same template as in my original post.

slack, php and json - Valid Markup for iterating app selections

I've been trying to create a slack app which takes the basic information of the name and sku of the product and places it within a select box that appears in slack. Unfortunately my code to populate the valid json is going wrong somewhere when i try to itterate using a loop.
Valid Json is here:
{
"text": "Great! You want to find something!",
"attachments": [
{
"text": "Please type what you want to find",
"fallback": "Sorry! Cant do that at the moment!",
"callback_id": "cg_selectproduct",
"color": "#3AA3E3",
"attachment_type": "default",
"actions": [
{
"name": "cg_choice",
"text": "Find Product",
"type": "select",
"options": [
{
"text": "option1",
"value": "option1"
},
{
"text": "option2",
"value": "option2"
},
{
"text": "option3",
"value": "option3"
}]
}
]
}
]
}
This works perfectly fine without the iteration. I have no issues if i tell the app to go here. It displays all options correctly.
Invalid PHP
$check = ($dbh->prepare("SELECT * FROM product_list WHERE FAMILY='PARENT'"));
$check->execute();
$row = $check->fetchAll();
// execute a pdo search to find all product parents
$jsonInput = "";
foreach($row as $rows){
$jsonInput .= '"text"=>"' . $rows['PRODUCT_NAME'] . '", "value" => "' . $rows['SKU'] . '",';
}
$jsonInput = rtrim($jsonInput, ',');
//Create an iterative string which will contain the product names and skus, removing the comma at the end.
header('Content-Type: application/json');
//Set the content type to json
$optionSelect = array(
"text" => "Great! You want to find something!",
"attachments" =>array(
"text" => "Please type what you want to find",
"fallback" => "Sorry! Cant do that at the moment!",
"callback_id" => "cg_selectproduct",
"color"=> "#3AA3E3",
"attachment_type" => "default",
"actions" => array(
"name" => "cg_choice",
"text" => "Find Product",
"type" => "select",
"options" => array($jsonInput)
)
)
);
//Create and itterate the options for the selection so it's populated
print_r(json_encode($optionSelect));
//print to show json
I'm not 100% sure where i'm going wrong with this. Maybe i'm thinking about a minor part a little too much. Can anyone here help me with where i'm going wrong?
$jsonInput = [];
foreach($row as $rows) {
$jsonInput[] = array(
'text' => $rows['PRODUCT_NAME'],
'value' => $rows['SKU']
);
}
// ...........
"options" => $jsonInput

MongoDB using only map without reduce in PHP

In mongoDB i have two collection users and posts following this structure:
Posts
{
_id: ObjectId(""),
subject: "some post",
content: "here is the content",
user_id: "4351"
}
Users
{
user_id: "4351",
name: "John Marks",
picURL: "http://...",
aboutme: "historian of the future"
}
needing to get the posts in array with name.
db.posts.find().map(function(newPost){
newPost.name = db.users.findOne({user_id: newPost.user_id}).name;
return (newPost);
})
I wrote this code and it's work in mongoshell well returning this result:
{
_id: ObjectId(""),
subject: "some post",
content: "here is the content",
user_id: "4351",
name: "John Marks"
}
but i could not apply in php. You can't just simple get the output of the map function. It requires reduce function and output collection for the returning value.
Edit:
$map = new MongoCode('
function(newPost) {
newPost.username = db.users.findOne({user_id: newPost.user_id}).name;
return newPost;
}
');
post = $app->mongo->command(array(
"mapreduce" => "posts",
"map" => $map,
"reduce" => '',
"out" => array("inline" => 1)
));
var_dump($post);
This code must be work but accessing another collection in map function via 'db' is forbidden after mongo 2.4 release. That's why i changed my approach. Instead of using map/reduce, handled with php. Added posts user_ids to array and get the users information with following code.
$userInf = $app->mongo->selectCollection("users")->find(
array('user_id' => array('$in' => $user_ids)),
array("_id" => 0, "user_id" => 1, "name" => 1, "picURL" => 1)
);

Create flot on PHP data

I would like to create a flot bar graph based on a php output. I managed to output data from php, but I would also like to use labels and display them on the xaxis. For some reason the output of the code below is invalid. The labels show up, but the bars and xaxis labels do not.
PHP:
function getOverview() {
$arr[] = array(
'label' => "Label 1",
'data' => array(0, 1)
);
$arr[] = array(
'label' => "Label 2",
'data' => array(1, 2)
);
echo json_encode($arr);
}
Output:
[{"label":"Label 1","data":[0,1]},{"label":"Label 2","data":[1,2]}]
jQuery:
$(document).ready(function(){
$.ajax({
url: 'http://localhost/getOverview.php',
method: 'GET',
dataType:"json",
success: onOutboundReveived
});
function onOutboundReveived(series)
{
var options = {
series: {
bars: {
show: true,
barWidth: .1,
align: 'center'
}
},
xaxis: {
tickSize: 1
}
};
$.plot("#chart_filled_blue", series, options);
}
});
Can anyone help me?
You've got a couple problems:
1.) Series data needs to be an array of arrays. Not just a single array:
'data' => array(array(1, 2))
This is, of course, so a series could have more than one point (even though your's has a single point).
2.) To get xaxis labels, you have two options. One, use the categories plugin. Two, manually provide the tick labels:
ticks: [[0, "zero"], [1.2, "one mark"], [2.4, "two marks"]]
In your situation I'd just use the category plugin. You'll need to modify the final data to:
{"label":"Label 1","data":[["Label 1",1]]}
or in the PHP:
$arr[] = array(
'label' => "Label 1",
'data' => array(array("Label 1", 1))
);
Here's a fiddle.
I think, your output has an incorrect format. Try this:
[
{
label: "Label 1",
data: [[0,1]]
},
{
label: "Label 2",
data: [[1,2]]
}
]

Categories