How can I use decoded JSON data inside PHP? - javascript

Using this plugin I need to draw an audio waveform with pre-rendered data.
I stored JSON data inside MySQL as {"sample_rate":44100,"samples_per_pixel":4410,"bits":8,"length":2668,"data":[0.13,0.19,0.15,0.11,0.13,0.13,0.24,0.35 ...]}
So I tried:
PHP
$json = $row['wave'];
$json_array = json_decode($json);
$json_wave = implode(',', $json_array->data);
HTML
<div data-track-wave="'.$json_wave.'" id="play'.$row['id'].'" class="track"></div>
JS
function createWaveform(json) {
$( "#waveformbottom" ).empty();
var linGrad = document.createElement('canvas').getContext('2d').createLinearGradient(0,0,0,170);
linGrad.addColorStop(0, '#ff3b25');
linGrad.addColorStop(0.5, '#ff0018');
var wavesurferbottom = WaveSurfer.create({
container: document.querySelector('#waveformbottom'),
waveColor: '#b3b3b3',
progressColor: linGrad,
backend: 'MediaElement',
mediaType:'audio',
height:'48',
cursorColor:'#fff',
cursorWidth:'0',
normalize:true,
barWidth:'2'
});
//Set peaks ! THE PROBLEM !
wavesurferbottom.backend.peaks = [json];
//Draw peaks
wavesurferbottom.drawBuffer();
$(window).resize(function(){
if($(this).width() != width){
widthbottom = $(this).width();
wavesurferbottom.drawer.containerWidth = wavesurferbottom.drawer.container.clientWidth;
wavesurferbottom.drawBuffer();
}
});
}
$(document).on('click touchend', '.track', function(e) {
var wave_data = $(this).data('track-wave');
createWaveform(json);
e.preventDefault();
});
A debug of my wave_data shows that is correct like 0.01,0.13,0.19,0.15,0.11,... however the waveform is not drawn.
Instead if I set wavesurferbottom.backend.peaks = [0.01,0.13,0.19,0.15,0.11,...];it works.
I'm not a JSON expert, what am I doing wrong?

The difference is that one is a string (which isn't valid JSON anyway - it's just a list of comma separated numbers):
data-track-json="0.01,0.13,0.19,0.15,0.11"
var json = $(this).data('track-json'); // a string
And the other is a JS array:
var x=[0.01,0.13,0.19,0.15,0.11];
A simple approach is to split it by , - that'll convert your string into the JS array that you need, like so:
var samples = $(this).data('track-json').split(','); // Renamed because it's not JSON
..
createWaveform(samples);
It's also worth noting that you'll get an array of strings rather than an array of numbers, but many JS libraries handle that. If you wanted to go the JSON route, then make sure your attribute contains square brackets:
data-track-json="[0.01,0.13,0.19,0.15,0.11]"
The PHP to create that could look like this:
$json_wave = '['.implode(',', $json_array->data).']';
Then use a JSON.parse call to convert it into a suitable array of number types:
var samples = JSON.parse( $(this).data('track-json') );

If you still want to use JSON
PHP
$json = $row['wave'];
$object = json_decode($json);
$json_wave = json_encode($object->data);
This is a JSON string, presumably something like [1,2,3,4]
HTML unchanged
<div data-track-name="'.$row['name'].'" data-track-id="'.$row['id'].'" data-track-json="'.$json_wave.'" id="play'.$row['id'].'" class="track song-play-btn playthistrack"></div>
JS parse the JSON where you've identified the problem
//Set peaks ! THE PROBLEM !
wavesurferbottom.backend.peaks = JSON.parse(json);
wavesurferbottom.backend.peaks will be an array of Numbers - presumably what the rest of the code expects

Related

javascript - convert string to json array

I was using s3 select to fetch selective data and display them on my front end .
I converted array of byte to buffer and then to string like below as string
let dataString = Buffer.concat(records).toString('utf8');
the result i got was string like below
{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"}
{"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"}
{"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"}
{"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"}
{"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"}
{"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"}
{"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"}
{"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"}
{"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"}
{"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"}
{"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"}
{"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}
Now i want to convert them to json array , i got a solution like below
let dataArray = dataString.split('\n');
//remove white spaces and commas etc
dataArray = dataArray.filter(d=> d.length >2);
//change string to json
dataArray = dataArray.map(d=> JSON.parse(d));
Now the problem is that i have splitted them with new line and wont work if the json is compressed or data itself can have new line.
What is the best way to handle this situation. i want the output like below
[{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"},
{"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"},
{"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"},
{"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"},
{"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"},
{"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"},
{"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"},
{"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"},
{"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"},
{"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"},
{"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"},
{"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}
]
#sumit
please take a look at this solution.
let dataString=`{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"}
{"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"}
{"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"}
{"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"}
{"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"}
{"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"}
{"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"}
{"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"}
{"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"}
{"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"}
{"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"}
{"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}`;
let dataArray = dataString.match(/{(?:[^{}]*|(R))*}/g);
dataArray = dataArray.map(d=> JSON.parse(d));
console.log(dataArray);
Yeah, it is not a very good idea to concatenate objects into a string like that. If you don't have any other choice, however, something like that should do the trick:
const initialString = `{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"}
{"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"}
{"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"}
{"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"}
{"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"}
{"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"}
{"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"}
{"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"}
{"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"}
{"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"}
{"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"}
{"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}`;
const json = `[${initialString.replace(/}\s*{/g, '},{')}]`;
const array = JSON.parse(json);

how can i convert my data in javascript server side to json object and array?

i'm working with xpages and javascript server side i want to convert the fields in format json then i parse this dat and i put them in a grid,the problem is that these fields can contains values :one item or a list how can i convert them in json ?
this is my code :
this.getWFLog = function ()
{
var wfLoglines = [];
var line = "";
if (this.doc.hasItem (WF.LogActivityPS) == false) then
return ("");
var WFLogActivityPS = this.doc.getItem ("WF.LogActivityPS");
var WFActivityInPS = this.doc.getItem ("WFActivityInPS");
var WFActivityOutPS = this.doc.getItem ("WFActivityOutPS");
var WFLogDecisionPS = this.doc.getItem ("WF.LogDecisionPS");
var WFLogSubmitterPS = this.doc.getItem ("WF.LogSubmitterPS");
var WFLogCommentPS = this.doc.getItem ("WF.LogCommentPS");
var WFLogActivityDescPS = this.doc.getItem ("WF.LogActivityDescPS");
var Durr =((WFActivityOutPS-WFActivityInPS)/3600);
var json= {
"unid":"aa",
"Act":WFLogActivityPS,
"Fin":WFActivityOutPS,
"Durr":Durr,
"Decision":WFLogDecisionPS,
"Interv":WFLogSubmitterPS,
"Instruction":WFLogActivityDescPS,
"Comment":WFLogCommentPS
}
/*
*
* var wfdoc = new PSWorkflowDoc (document1, this);
histopry = wfdoc.getWFLog();
var getContact = JSON.parse(histopry );
*/ }
Careful. Your code is bleeding memory. Each Notes object you create (like the items) needs to be recycled after use calling .recycle().
There are a few ways you can go about it. The most radical would be to deploy the OpenNTF Domino API (ODA) which provides a handy document.toJson() function.
Less radical: create a helper bean and put code inside there. I would call a method with the document and an array of field names as parameter. This will allow you to loop through it.
Use the Json helper methods found in com.ibm.commons.util.io.json they will make sure all escaping is done properly. You need to decide if you really want arrays and objects mixed - especially if the same field can be one or the other in different documents. If you want them flat use item.getText(); otherwise use item.getValues() There's a good article by Jesse explaining more on JSON in XPages. Go check it out. Hope that helps.
If an input field contains several values that you want to transform into an array, use the split method :
var WFLogActivityPS = this.doc.getItem("WF.LogActivityPS").split(",")
// input : A,B,C --> result :["A","B","C"]

JSON format issue in JavaScript

Following is my JavaScript code to get JSON data:
$(document).ready(function()
{
$.support.cors = true;
$.getJSON('http://example.com/root_dir/test_json.php', function(data1)
{
alert("data1= "+data1);
});
});
but the above alert shows me JSON in following format-
If I hit my php script URL in browser, it shows JSON data in expected formate as shown below-
[{"name":"AB","std":"7","number":"82"},{"name":"CD","std":"9","number":"90"},{"name":"PQ","std":"12","number":"79"}]
Following is my test_json.php code-
<?php
//Create an array
$json_response = array();
$row_array['name'] = 'AB';
$row_array['std'] = '7';
$row_array['number'] = '82';
array_push($json_response,$row_array);
$row_array['name'] = 'CD';
$row_array['std'] ='9';
$row_array['number'] = '90';
array_push($json_response,$row_array);
$row_array['name'] = 'PQ';
$row_array['std'] = '12';
$row_array['number'] = '79';
//push the values in the array
array_push($json_response,$row_array);
echo json_encode($json_response);
?>
getJSON decodes the JSON into a JavaScript data structure.
Concatenating it with a string will implicitly call toString() on it. That will turn arrays in to a comma-seperated format and plain objects into "[Object object]".
Nothing is going wrong. That is the expected behaviour.
If you want to see the data in JSON format, then use JSON.stringify(data) or use .ajax instead of .getJSON and access the raw text data in the jqXHR object.

Parse json array using javascript

I have a json arry
var students = {"apResults":[{"offid":"267","item_name":"","offer_name":"fsdfsf","stlongitude":"77.5945627","stlatitude":"12.9715987"},
{"offid":"265","item_name":"","offer_name":"vess offer shops","stlongitude":"","stlatitude":""},
{"offid":"264","item_name":"","offer_name":"vess ofer shop","stlongitude":"","stlatitude":""},
{"offid":"263","item_name":"","offer_name":"ofer frm vess","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"262","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"261","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"260","item_name":"","offer_name":"offer1","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"259","item_name":"","offer_name":"offer","stlongitude":"77.5943760","stlatitude":"12.9716060"}]}
How i can parse this json arry using json.parse. I have tried this code
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults);
var offid = contact.offid;
alert(offid)
}
But its giving an error JSON.parse: unexpected character.Edited my question
That's not a json string, that's a regular javascript variable:
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults[i].offid);
alert(contact)
}
JSON parses strings, not objects/arrays.
why need parsing when you can access it like students.Maths[i].Name
students is not a JSON array, it's an actual array. You don't have to parse because it's not a string. So you can access directly to the data you need:
for(i=0;i<students.Maths.length;i++) {
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
You can't parse students because is not a JSON. It's simple object.
However this will work:
var students = JSON.stringify(students); // if you want to send data
students = JSON.parse(students); // after receiving make a object from it
//use like any object
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
Of course it doesn't make sense to write it that way unless you send students data to other site or program.
Edit:
You don't need JSON in this code at all. But if you want to test JSON.parse() do it this way:
var students = { ... } // your data
var students = JSON.stringify(students); // students is `object`, make it `string`
students = JSON.parse(students); // now you can parse it, `students` is object again
for(i=0;i<students.apResults.length;i++) {
var contact = students.apResults; // no JSON
var offid = contact.offid;
alert(offid)
}
That should work.
What you have is a javascript object. So, you won't need the JSON.parse
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i]);
var fullname = contact.Name;
alert(fullname)
}
this should be ok
The idea of JSON is for the exchange of objects represented as a structured string (in a nutshell). What you've got there is simply an object. It's unnecessary (and impossible) to parse and object that isn't JSON into a javascript object; what you have is the outcome of what you would expect from a parsed JSON string.

javascript arrays on gmaps

i'm newbie in javascript so, in this example exists the geometrycontrols.js (for global controls) and markercontrol.js (for marker controls)
my problem is identify the arrays where "data" is saved...
at the reference i see a savedata function but i have no idea how work with this function...
on the other side, in test.html if i've the outup on the Glog startup and output "data", and let me thinking that comes from array...
My objective is save the coordinates and other all atributes to mysql database, and when i discover where are "data" is the easy part.
if someone worked with this example (or not) can help me i'm grateful
ps: i'm really a newbie on javascript :P
edit1:
I was out for a time, and now I focus in geometrycontrols.js specially in: GeometryControls.prototype.saveData = function(opts){
var me = this;
if(opts.allData === true){
//me.saveAllData();
} else {
//construct a json data record
var geomInfo = opts.geomInfo, index = opts.geomInfo.index;
var record = geomInfo.storage[index];
var recordJSON = {};
recordJSON.type = record.type;
recordJSON.coordinates = [];
//determine geometry type, and copy geometry appropriately
if(record.type === "point"){
recordJSON.coordinates.push({lat:record.geometry.getLatLng().lat(),lng:record.geometry.getLatLng().lng()});
alert(recordJSON.coordinates);
} else {
alert("is not point");
var vertex;
for(var i=0;i<record.geometry.getVertexCount();i++){
vertex = record.geometry.getVertex(i);
recordJSON.coordinates.push({lat:vertex.lat(),lng:vertex.lng()});
}
}
//add title and description
recordJSON.title = record.title[0];
recordJSON.description = record.description[0];
//TODO add styles
recordJSON.style = ""; //TODO} //TODO Make separate prototype function?function postData(data){
//TODO
me.debug(data);
//alert(recordJSON.coordinates);
//alert(data);
};postData(me.serialize(recordJSON));}; `
When I alert(recordJSON.coordinates), the outupt is [object Object] and i've no idea why, in theory this array contains the coordinates...
Here is some code I have used to send the data to MySQL. It uses a little bit of jQuery to do the ajax magic (the line starting with the dollarsign is jQuery).
function postData(data){
me.debug(data);
var dataString = JSON.stringify(data);
me.debug(dataString);
$.post('storage.php', { data: dataString });
};
postData(recordJSON);
As you can see I've modified the way the 'recordJSON' object gets sent to the postData function a bit too: I've removed the serialise function.
Next, create a PHP file (called 'storage.php' in my case) and put this in it:
<?php
$received = json_decode($_POST['data'], true);
echo "just received " . $received['name'];
?>
You now have an array in PHP that you can do with as you please.
In the examplecode above I've modified the jQuery post function a bit, so if it doesn't work, look there.
The data is stored in JSON format in this file: http://gmaps-utility-library-dev.googlecode.com/svn/trunk/geometrycontrols/examples/data/testdata.js -- it's pretty much self-documenting, just follow the example to set your coordinates.
Note that if you need to find the latitude and longitude for a given address this is a good site: http://itouchmap.com/latlong.html

Categories

Resources