JS read json file and use as an object - javascript

I'm trying so get the number of items in the array inside this piece
JSON
{
"collection" : [
{
"item": "apple"
},
{
"item": "banana"
}]
}
Using the following JS (NodeJS):
Updated with answers from user 'elssar'
var data = JSON.parse(fs.readFileSync(filePath));
console.log(data.collection.length);
Expected result: 2
Without specifying the encoding data will be a buffer instead of string (thanks to user nils). JSON.parse should work for both. Now I'm getting an error Unexpected token ? at Object.parse (native). Any idea how to fix this? (using Node 5.2.0)

You need to parse the content of the file to JSON.
fs.readFile(filePath, function (error, content) {
var data = JSON.parse(content);
console.log(data.collection.length);
});
Or
var data = JSON.parse(fs.readFileSync(filePath));
Alternatively, you could just require json files (the file extension needs to be .json)
var data = require(filePath);
console.log(data.collection.length);

Related

Access JSON object from another file in Javascript

Perhaps a simple question but I am still new to JS / nodeJS.
I have a script that is doing some basic string matching (dict.js), and I am trying to access a JSON formatted object from another file (words.json) to iterate through.
The directory structure looks like:
scratch
- algorithms
- dict.js
- utilities
- words.json
The contents of the files are:
words.json
{"a": 1,"aa": 1,"aaa": 1,"aah": 1,"aahed": 1,"aahing": 1,"aahs": 1,"aal": 1}
dict.js
decode (password) {
const jsonData = require('../utilities/words.json');
myObj = JSON.parse(jsonData);
for (const x in myObj) {
console.log(x)
// compare password against item in words.json
}
console.log(Object.keys(myObj).length)
return "stub";
}
I am getting an error in developer tools when I create a block (this is the backend to a block in Scratch) that uses this Decode function.
Uncaught SyntaxError: Unexpected token o in JSON at position 1
Thanks
In nodejs environment you can directly import json file data without parsing it. For exaple:
const myObj = require('../utilities/words');
This gives you the data in your json file as a ready-to-go object.
In your case, you are trying to parse json object with JSON.parse() which expects stringified json. So just remove the part JSON.parse(jsonData);

how to solve problem getting json object element

I have a json object that i want to use.
{
"type": "PROVIDER_PAYLOAD",
"message": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkOTQ3OTg4N2RlMGRkMDc4ZjEzM2FmNyIsImVtYWlsIjoiYWxzb25nZHVuc3RhbjJAZ21haWwuY29tIiwicm9sZSI6IkNVU1RPTUVSIiwiaWF0IjoxNTcwMDI3MDA4fQ.FcpoBPmhTSX535bNgE2ezCCWsNFPjEhc87hM4y6WadM"
}
so when i try to access it using
console.log("Postback: " + payload.type)
but i get an error of
Postback: undefined
i have looked over some resources on the web and most of them do it this way and it works but i am not sure why mine is not giving the value for type
thanks in advance
Subh is right. You have to parse the JSON into an object before accessing type using payload.type syntax.
So, let's say you have the following:
let payload = {
"type": "PROVIDER_PAYLOAD",
"message": "eyJhbGciOiJIUzWadM"
}
You have to convert it into a JS object using JSON.parse:
let payloadObj = JSON.parse(payload);
Now, if you do payloadObj.type, you should be fine.
console.log(payloadObj.type); // PROVIDER_PAYLOAD
It should work fine.
UPDATE: ERROR: SyntaxError: Unexpected token a in JSON at position 0
If you are getting this error, try following to Parse the payload.
let payloadObj = JSON.parse(JSON.stringify(payload))
It should solve the problem for you.

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

Python json.dump() to javascript JSON.parse()

Problem Summary: can't parse through string that's formatted as a JSON object from .json file
Long Version:
I have some tweets I'm processing with Python where I create a json file I'm wanting to pass into d3.js and parse. I'm writing the tweets I get, into a file, so I have to serialize them with the json.dump() command in Python before I write them to a file.
Python
def on_data(self, data):
f = open("tweets.json","a")
tweet = json.loads(data)
d = {
"created": tweet["created_at"],
"text": tweet["text"]
}
final_tweet = json.dumps(d)
f.write(final_tweet)
f.close()
return True
However when I get the json file and try to grab it in my d3.json("tweets.json") it prints out the correct json format in the file:
{
tweet:[
{"key":"value"},
{"key":"value"}
]
}
but I cannot parse the data with the code I'm using because console.log(JSON.parse(data)) does not print out any object value.
d3.text("tweets.json", function(error, data){
if (error) return console.warn(error);
console.log("hello3");
console.log(JSON.parse(data));
});
EDIT I edit the file that gets written to by manually adding braces at the top and bottom.
Use this Json instead and check your Json data here
{
"keys":[
{"key":"value"},
{"key":"value"}
]
}

Categories