JavaScript: read and write json file - javascript

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);

Related

NodeJs JSON parsing issue

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);

Reading JSON data from JS file

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

JSON parsing and stringify

I am currently working on a Javascript project where I have to parse tons of data. The project requires that I parse some JSON data and bring specific data into another array. Right now, I am using the JSON.stringify method and I can console.log all of the data that I need. The data looks something like this:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-85.3865810000125,
33.90171899971196
],
[
-85.38659500025622,
33.9017919996593
],
yes, this is not all that data-it is about 1200 pages long! I only pasted in the top segment of it. All I really need is how to get to the coordinates aspect of it and into an array. So what I am currently doing is this:
var work = JSON.stringify(response, null, 4)
console.log(work);
Which gives me the above response. However, I am not that familiar with JSON.stringify so if I do:
console.log(work.type);
Attempting to see what the value is for type, I get a response of undefined. Now if I try doing this:
var work = JSON.parse(response)
console.log(work);
I get a response of: VM296:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
Thus, I cannot get the data parsed which I want to get to which will be the coordinates data. Any help with using stringify would great help me. I have read a lot about how it turns the data into a string but have not really seen a lot about how to parse it. Do I have to use parse? Thank you for your help!
You dont' have to use stringify or parse for this. The response object you are receiving is already a javascript object so you can reference its properties normally
response.type; // => "FeatureCollection"
If you try and stringify the response it will lose its type property, for instance:
typeof "some string".someProperty; // => undefined

Print data from json file

I have json file with given data (total.json)
var data = {"trololo":{"info":"61511","path".... }}
I need to get object "info" and then print data "61511" in alert window
I include my json like
var FILE = 'total'
var data_file_names = {};
data_file_names[FILE] = 'total.json';
And then i use it like
var data_trololo = data_file_names[FILE];
Plese, help me print object "info". Maybe there is another way to solve this problem
You need to make an ajax call to the json file. Then you can access the array like the below example.
Note : Your json wasn't properly formatted.
var data = {
"trololo":{
"info": ["61511","path"]
}
};
console.log(data.trololo.info[0]); //this one will print 61511
Usually one can make an ajax call to read the file on the server.
But if you are ok with using HTML5 features then go through the link find out how to read the file on the browser itself. Though File API being part of HTML5 spec is stable across browsers.
http://www.html5rocks.com/en/tutorials/file/dndfiles/

To get JSON data from Javascript file

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.

Categories