Use python to add to javascript array in javascript file - javascript

I have this array stored in versions.js
var cc_versions = [
"2016-01-22",
"2016-01-21",
];
var cs_versions = [
"2016-01-23",
"2016-01-21",
];
I have been trying to figure out a way to write new data to the top of the array inside the javascript file with python. I run a python script on my computer almost every day and I want to update this array when I run it so that I can have a website load the versions. Is it possible to do this? I know I could write to the file, but it would just go to the bottom of the file outside of the array. Also there will be multiple arrays, so I'm trying to find some python script that can interact with a javascript file so I can target specific arrays.

You could also try using Genshi template language. One of the tags there is
<?python ... ?>
for example:
<?python
import json
dateInit = []
selectInit = []
for fi in form_items:
if (fi["type"] == "date"):
dateInit.append(fi["id"])
if "attrs" in fi and "format-select" in fi["attrs"]:
selectInit.append(fi["id"])
if not "attrs" in fi:
fi["attrs"] = {}
jsonDateInit = json.dumps(dateInit)
jsonSelectInit = json.dumps(selectInit)
?>
Your response should contain form_items dictionary processed somewhere on the back-end. Then in javascript you can 'accept' the variables using '$'-sign:
var dateitems = JSON.stringify($jsonDateInit);
var select_items = JSON.stringify($jsonSelectInit);

import json
NEW_VARIABLES = [1, 2, 3]
with open('your/json/file.json') as data_file:
json_data = json.load(data_file)
# insert at the beginning of the list
json_data['cc_version'].insert(0, 'something new')
json_data['cs_version'] = NEW_VARIABLES + json_data['cs_version']
# write to json file after modifying data
with open('your/json/file.json', 'w') as output_file:
json.dump(json_data, output_file)

I ended up using json as suggested in the comments
import json
with open("cc_versions.txt") as data:
json = json.load(data)
dates = json["dates"]
dates.append("2016-01-21")
dates = set(dates)
dates = sorted(dates, key=lambda d: map(int, d.split('-')))
dates = dates[::-1]
import json
with open("cc_versions.txt", "w") as outfile:
json.dump({'dates':dates}, outfile, indent=4)

Related

I'd like to code the array value I received from Python into JS and print it out on the web page

It is to draw a plot graph on a web page using Python and js code.
Here's my python code
from bottle import route, run, request, redirect, template
import pymysql as sql
#route('/print')
def show_print():
db = sql.connect(host='localhost', user='root', password='1234', db='testdb')
if db is None:
return template("index.tpl", text="Non", x_value=[], y_value=[])
else:
query = "select * from testdata;"
cur = db.cursor()
n = cur.execute(query)
tpl_no=[]
tpl_date=[]
tpl_hum=[]
tpl_tmp=[]
for i in range(n):
value = cur.fetchone()
tpl_no.append(value[0])
tpl_hum.append(value[2])
return template("index.tpl", x_value = tpl_no, y_value = tpl_hum)
db.close
And MySQL test data table content:
enter image description here
and plotly.js
<h1> {{x_value}} Hi There</h1>
<h1> {{y_value}} Hi There</h1>
<div id="myPlot" style="width:200;height:800px;"></div>
<script type="text/javascript">
var x_arry = new Array();
var y_arry = new Array();
for(var i = 0; i < {{x_value}}.length; i++){
x_arry.push({{x_value}}[i]);
}
for(var i = 0; i < {{y_value}}.length; i++){
y_arry.push({{y_value}}[i]);
}
var data = [{
x: x_arry,
y: y_arry,
mode: "lines"
}];
var layout = {
xaxis:{title:"X: Number"},
yaxis:{title:"Y: Hum"},
title:"This is my graph"
};
Plotly.newPlot("myPlot", data, layout);
I made it like this. But I can't see the plot graph on the web page
The x_arry value has been output normally in the js code.
However, the plot graph is not drawn on the web page because the y_arry value is not printed. I want to solve this.
I would recommend making two changes to your code.
Firstly, you'll need to convert the Decimal values you are getting from the database to Python floats, by replacing the line
tpl_hum.append(value[2])
with
tpl_hum.append(float(value[2]))
Secondly, the most reliable way to get data from your Python code to your JavaScript code is to get Python to serialize the data as a JSON string, and put this in your template. Try replacing the following line in your Python code
return template("index.tpl", x_value = tpl_no, y_value = tpl_hum)
with
json_data = json.dumps({"x_array": tpl_no, "y_array": tpl_hum})
return template("index.tpl", json_data=json_data)
You'll also need to add import json to your Python code.
The JavaScript within your template then becomes:
var jsonData = {{json_data}};
var data = [{
x: jsonData.x_array,
y: jsonData.y_array,
mode: "lines"
}];
var layout = {
xaxis:{title:"X: Number"},
yaxis:{title:"Y: Hum"},
title:"This is my graph"
};
Plotly.newPlot("myPlot", data, layout);
You don't need the loops to read the data into variables such as x_arry and y_arry. (In fact, it's arguable you wouldn't have needed them before.)
Disclaimer: I haven't tested this.

Creating new instead of overwriting

Hi!
I'm creating a warn system and I want to save warns to JSON file. The problem is that when I'm trying to make a new object in something it overwrites.
My code:
const warnObject = JSON.parse(fs.readFileSync('./data/data.json'));
const id = "739176"
const length = Object.keys(warnObject[id]).length + 1
warnObject[id] = {}
warnObject[id][length] = {}
warnObject[id][length]["reason"] = "This is a reason."
warnObject[id][length]["date"] = new Date().toLocaleString();
fs.writeFileSync('./data/data.json', JSON.stringify(warnObject));
And here's my JSON file:
{"739176":{"2":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}}
So I want to instead of overwriting warn number 2 create new like this
{"739176":{"2":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}, {"3":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}}
If you want to have multiple warning objects under the id "739176", you would need to format your json file in order to have an array associated to your id, such as :
{
"739176":[
{"2":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}},
{"3":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}
]
}
So, once you have formatted your file this way, you will be able to get the array referred by the id, and push objects to it like this :
warnObject[id].push({"4":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}});

How to get a string from a BS4 scrape

recently I scraped a text/javascript that contains the following code:
var spConfigDisabledProducts = [-1
, '294653', '294655', '294656', '294657', '294658', '294659', '294660', '294661', '294662', '294663', '294664', '294666', '294667', '294668', '294669', '294670', '294671', '294672', '294673' ];
{"attributes":{"959":{"id":"959","code":"aw_taglia","label":"Taglia","options":[{"id":"1717","label":"15","price":"0","oldPrice":"0"...
I just want to get all the numbers inside var spConfigDisabledProducts excluded -1, so I tried this:
js = soup.find_all('script')[25].text.replace(',}', '}').replace(',]', ']').strip()
js = json.dumps(js)
obj = json.loads(js)
data_oos = obj.split('var spConfigDisabledProducts = [-1,')
data_oos = data_oos[1].split("];")
But it returns the entire javascript, not only var spConfigDisabledProducts.
How can I fix this?
Thanks in advance
You could regex out string representation of list and convert to actual list then slice
import re, json, ast
s = '''var spConfigDisabledProducts = [-1
, '294653', '294655', '294656', '294657', '294658', '294659', '294660', '294661', '294662', '294663', '294664', '294666', '294667', '294668', '294669', '294670', '294671', '294672', '294673' ];
{"attributes":{"959":{"id":"959","code":"aw_taglia","label":"Taglia","options":[{"id":"1717","label":"15","price":"0","oldPrice":"0"'''
p = re.compile(r'spConfigDisabledProducts = (\[[\s\S]*?\])')
data = ast.literal_eval(p.findall(re.sub('\n|\s{2,}','',s))[0])
print(data[1:])

How can I use decoded JSON data inside PHP?

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

Edit json in js/node.js?

I am working on an nodejs app which reads data from a json file. Now I want to edit this json file in js (write to it). How do I do this ?
Here is my js code: `
var fs = require("fs")
//function for file input
function getFile(filename) {
var data = fs.readFileSync(filename,"ascii")
return data }
//parsing json
var jsonString = [getFile("File.json")]
var jsonObj = JSON.parse(jsonString)`
Modify the jsonObj as you want, create a new object or whatever, then write the file:
fs.writeFileSync("File.json", jsonData);
This will overwrite the file if it exists, so that way you edit the file.
You can load a json file by requiring it.
var contents = require('/path/to/file.json');
Iterate contents just like a regular object.
A JSON object, when parsed is, like any other JS object. Use object dot notation to access any data you want.
For example a value:
console.log(isonObi.something.value)
For example a value in an array:
console.log(isonObi.something[0].value)
From eyp
Modify the jsonObj as you want, create a new object or whatever, then write the file:
fs.writeFileSync("File.json", jsonData);
This will overwrite the file if it exists, so that way you edit the file.
With nodeJS, you can require a JSON file.
Supposing you get this JSON file :
//test.json
[
{
"name": "toto",
"code": "4"
},
{
"name": "test",
"code": "5"
}
];
Then, you can require this file and perform some modification :
var json = require('./test.json');
json.forEach(function(elm){
elm.name = 'test';
});

Categories

Resources