I am uploading one JS file using HTML input file tag. I am reading the data in Python. Since in my data var acb_messages is written, I am not able to parse it. And I want to use this variable name to get the data so I can remove it.
var acb_messages = {"messages": [{
"timestamp": 1475565742761,
"datetime": "2016-10-04 12:52:22 GMT+05:30",
"number": "VM-449700",
"id": 1276,
"text": "Some text here",
"mms": false,
"sender": false
}
]}
How can I parse it in Python and then how can I use it?
Two approaches that I would try if I were at your place -
Convert my .js file to .json file and then using method suggested by #Sandeep Lade.
Reading .js file as string, cropping out the value part and then using json.loads(<cropped part>) as suggested by #rahul mr.
Here is how to achieve 2nd solution -
import json
with open('your_js_file.js') as dataFile:
data = dataFile.read()
obj = data[data.find('{') : data.rfind('}')+1]
jsonObj = json.loads(obj)
What's happening here is that you are finding first reading your .js file (that contains js object that needs to be converted into json) as string, find first occurence of { and last occurence of }, crop that part of string, load it as json.
Hope this is what you are looking for.
Warning - Code works only if your js file contains js object only.
The options above are correct, but the JSON syntax in JS can be a little different than in Python:
example.js:
property.docs = {
messages: {
timestamp: 1475565742761,
datetime: "2016-10-04 12:52:22 GMT+05:30",
number: "VM-449700",
id: 1276,
text: "Some text here",
mms: false,
sender: false
}
};
Therefore we need one more tweak that I found at: How to convert raw javascript object to python dictionary?
The complete code should be:
import json
import demjson
with open('example.js') as dataFile:
data = dataFile.read()
json_out = data[data.find('{'): data.rfind('}')+1]
json_decode = demjson.decode(json_out)
print(json_decode)
import json
jsonfile=open("/path/to/json file")
data=json.load(jsonfile)
the above code will store will store your json data in a dictionary called data. You can then process the dictionary
Related
I have generated json file from my consumer pact in javaScript. When it's generating json file it doesn't contain what I expect. So, now I want to add block to my json file which I don't know how to do? Can someone here help me with that? so, basically I want to read json then create block and then write into json and save data
"path": {
"dataType": "String",
"expression": "data/xml/${id}",
"key": "request"
}
Thanks,
As #Barmar pointed out you can simply parse your JSON text and modify it.
let yourJsonText = "{...}"; // read in your json however you want
let yourJson = JSON.parse(yourJsonText);
// then modify your object
yourJson.path.newAttr = "something you like";
// parse it back to a JSON string
let yourUpdatedJsonText = JSON.stringify(yourJson);
I'm working on a discord bot right now that reads responses off of a JSON file. The basic format is as follows:
"matt":
{
"insults" : ["test 1",
"test 2",
"test 3",
"test 4"
]
},
I'm currently working on a function that allows a user to use the !addInsult command, followed by a string, which will then append onto the existing array.
My desired workflow is as such:
User types in the following: !addInsult test 5. This would then modify the JSON object of insults under matt to the following:
"matt":
{
"insults" : ["test 1",
"test 2",
"test 3",
"test 4",
"test 5"
]
},
Doing this will allow me to let my friends add data to my bot without needing me to manually edit the JSON every time we want something new.
What would the best way of going about this be? I've looked into this thing called push, but I don't really understand how that works.
This is what I have so far. I think I'm going in the right direction, but I'm not sure:
The following is established at the beginning of the script:
// contains the insults
var insults = require('./insults.json');
// get the insults from the json file specific to user
var insultsString = JSON.stringify(insults);
var json = JSON.parse(insultsString);
And here is the function that will be doing appending:
// command that allows users to add to the pool of insults
function addInsultCommand(args, receivedMessage)
{
// create an object that contains the information for the json file
json["bot"].push(["test"]);
receivedMessage.channel.send(json.matt.insults[0]);
}
so there is a misconception here; JS does not write to files.
You're using webpack, which let's you require the .json using a webpack loader, but this will ONLY work when using the dev server. This will not work when distributing your code, because the .json will will be encoded into your output bundle.
.js can not write a file for you ( except locally ), so what you need to do is two fold:
1) Download the .json from the webserver, without using a webpack loader.
2) modify the JSON data in memory
3) upload the JSON data to the web server for it to write the file for you.
In addition to this, I can not follow your example code. you reference receivedMessage.channel.send, but I do not see where this is defined. Is this some kind of discord integration? You may need to re-state your question along with a minimal proof of the issue with reproducible test code.
JSON.stringify will turn a javascript object into a JSON object. JSON.parse will do the opposite(turn a JSON object into a Javascript object). Assuming insults.json is a json object, you do not need to convert it into a string. You can just do JSON.parse(insults) to convert it into a javascript object.
I am not sure what you were intending to do with the args variable in addInsultCommand but I am going to ignore for now and give you some steps to follow below.
1) Turn JSON object(insults) into JS object
2) create a function that takes a JS object and a receivedMessage(the insult to add) and assigns it to the correct place in the JS object.
3) convert the JS object into JSON(using JSON.stringify) and replace the contents of insults.json with the the updated value.
I have a .json file where i have people's names stored. I'm reading the content from this file using the file system from Node Manager and then I'm trying to convert this json to string and parsing it to JS object. After parsing it to JS object i get as type string instead of object.
Here is the example json file :
{
"21154535154122752": {
"username": "Stanislav",
"discriminator": "0001",
"id": "21154535154122752",
"avatar": "043bc3d9f7c2655ea2e3bf029b19fa5f",
"shared_servers": [
"Reactiflux",
"Discord Testers",
"Official Fortnite",
"Discord API"
]
}
}
and here is the code for processing the data:
const string_data = JSON.stringify(fs.readFileSync('data/users.json', 'utf8'));
const data = JSON.parse(string_data);
console.log(typeof(data)); // <-- this line here shows the type of data as string
const results_array = Object.values(data);
where fs is the file system package from npm.
don't use JSON.stringify as it is further changing the string representation of JSON object. An example of what is happening is below
Imagine if you have a data in your file as shown below
{
"key": "value"
}
When you read the file (using readFileSync) and apply JSON.stringify, it is converted to a new string as shown below. You can notice that the double quotes are now escaped
"{\"key\": \"value\"}"
Now when you will parse it using JSON.parse then instead of getting the desired object, you are going to get back the same string you read from the file.
You are basically first performing and then undoing the stringify operation
Okay so fs.readFileSync returns a string so you dont need to use stringify
var fs = require('fs');
var read = fs.readFileSync('data/users.json', 'utf8');
console.log(read);
console.log(typeof(read));
const data = JSON.parse(read);
console.log(typeof(data));
You will see it returns an object
This works for me:
const data = JSON.parse(fs.readFileSync('data/users.json', 'utf8'));
console.log(typeof(data)); // <-- this line here shows the type of data as OBJECT
const results_array = Object.values(data);
I have a subject.js javascript file in which json data is stored:
Subject.js
Example:
Teacher = {
"Eng" : "English",
"Math" : "Maths",
"Sci" : "Science",
"SST" : "Social Studies",
"Hin" : "Hindi"
};
I want to read json data from this js file into another js file.
But I learnt that $.getJSON('filename.json', function(data) { is used to get data from json file but my json data is stored in js file. Can anyone tell me how to get started? I tried using getJson but can't get it to work.
There are two possibilities:
The file can just be included and use the teacher variable as if you ran the getJSON function.
The Teacher = and semi-colon at the end can be removed (verify it is a correct JSON structure) and save the file as .json. Assuming your server will send a JSON file, this should allow the file to be requested.
Remove the varibale declaration "Teacher =" and your js become a json content that can be called by $.getJSON
You simply need to include the file with your Teacher definition on the same page as your other JS file. Then you will have access to the variables defined in Subject.js. For instance:
<script src="Subject.js"></script>
<script>
console.log(Teacher.Sci)
</script>
would output Science to the javascript console.
JSON is not its own type in Javascript, it is simply a certain syntax for defining plain-old Javascript objects. JSON stands for JavaScript Object Notation. This is the JSON part of your example:
{
"Eng" : "English",
"Math" : "Maths",
"Sci" : "Science",
"SST" : "Social Studies",
"Hin" : "Hindi"
}
So when you set a variable equal to a JSON block as in your example, you are creating an object with those properties. As such, you can simply treat that JSON object like any other javascript object. The code you provided is the same as the following:
Teacher = new Object();
Teacher.Eng = "English";
Teacher.Math = "Maths";
Teacher.Sci = "Science";
Teacher.SST = "Social Studies";
Teacher.Hin = "Hindi";
$.getJSON, on the other hand, is used for converting a text file (or file output) in JSON notation into a javascript object, but that is not necessary in this case, as your JSON object is already created within the javascript code.
I am looking to store a JSON file locally on IOS/Android in a Phonegap(Cordova) application.
Basically, I retrieve a JSON file from the server ($.GETJSON) and I want to first store the JSON file and then retrieve and modify it.
I've looked at FileWriter but I don't see a mimetype... the only example gives text files.
Thanks in advance!
Nick
Nick, just use FileWriter.write to save your JSON data to disk. JSON is a text based file anyway so there is no need to set the mime type. When you are ready to load the file again use FileReader.readAsText. In your "onloadend" handler of the FileReader the method will be called with an event and event.target.result will be your JSON data. Then you'll do a
var myJson = JSON.parse(event.target.result);
to turn the text into a JSON object.
(for template or default settings) I just store them in seperate constant files so i don't have to use any special file utility addons or commands, super easy:
(function(){
angular.module('app').constant('settings_json',
{
"name":"settings",
"data":[
{
"set":"globals",
"share_diagnostics":true,
"user_prefs_save_cloud": true
},
{
"set":"user",
"fname":'',
"lname": '',
"telephone": '',
"email": ''
}
]
}
)})();
Then in your app: (after injecting 'settings_json')
var settings = angular.fromJson(settings_json);