I'm having trouble reading properties from JSON within NodeJS.
Feels like an obvious mistake I may be making..
The JSON is from this endpoint;
http://hypem.com/playlist/history/faisdotal/json/1/data.js
My code:
var request = require('request');
request("http://hypem.com/playlist/history/faisdotal/json/1/data.js", function (err, res, json) {
JSON.parse(json);
console.log(json["1"]["artist"]); // undefined
});
~
You need to store the returned value of JSON.parse:
json = JSON.parse(json);
console.log(json["1"]["artist"]);
I think you want:
json = JSON.parse(json);
It won't (and can't) simply update the value of the parameter. The .parse() routine returns the value parsed from the string you pass it.
JavaScript is purely call-by-value, so there's really no way it could possibly work the way your code is written.
Related
So i am trying to display a data from an API using JavaScript but got an undefined instead when i console.log(data) what i am getting is like below. its an object but some how its encapsulate as a string? Any idea how to covert this into a actual object i am new with JavaScript api so i am a bit confused.
{"msg":"{\"part\":\"test\",\"station\":\"test2\"}"}
I already tried to de serialize the data using JSON.parse(data) but no luck.
What you have posted is actually an object with a property msg which is a strigified JSON. In order to get proper json from this try obj.msg = JSON.parse(obj.msg); Assuming obj is the response variable you can name it what you want.
See below snippet.
{"msg":"{\"part\":\"test\",\"station\":\"test2\"}"}
const obj = {"msg":"{\"part\":\"test\",\"station\":\"test2\"}"} ;
console.log('Before parsing:' + typeof obj.msg); // string
obj.msg = JSON.parse(obj.msg);
console.log('After Parsing:' + typeof obj.msg); // object
Hope this helps :)
JSON.parse transforms a string-like-object to the object. So, it expects the whole of the object as a string. Which is not happening in your case.
You have an object key msg and its value is a string-like-object. So You need to convert the msg value to the JSON.
a couple of ways to try -
let resp = JSON.parse(data.msg)
or
return JSON.parse(data.msg)
I have an external json file which I am using to initialize a js object in a web app (using webpack).
To read the file im doing this:
var myObject = require('json-loader!constants/myfile.json')
The application needs to modify the object over time and occasionally needs to return to the original state. Due to this, I've found this to be the most performant way to initialize and reinitialize (deep clone) the object:
var clonedObject = JSON.parse(JSON.stringify(myObject))
This approach seems redundant - First load a json object then stringify the object only to load it again.
Is there a way to read the JSON file as a string and then JSON.parse the object (thus omitting the JSON.stringify step)?
You can use raw-loader to read a file as string:
var jsonString = require('raw-loader!constants/myfile.json');
var obj1 = JSON.parse(jsonString);
var obj2 = JSON.parse(jsonString);
You'll want to read the file contents first using a blob perhaps.
Get the text content, then use the JSON.parse(jsonString).
Honestly I am too ignorant to keep libraries in my head, and thus I read JSON files with fs like this:
var fs=require("fs");
var stuff=JSON.parse(fs.readFileSync("filename","utf8"));
And then it is pretty sure that someone could store the intermediate result of fs.readFileSync() if they wanted to:
var fs=require("fs");
var originaljson=fs.readFileSync("filename","utf8");
var stuff=JSON.parse(originaljson);
I have a snippet code with eval() as shown below:
var data = "{listUpdated:[],listConflictOrMerge:[]}"; //returned from Ajax
var results = eval("(" + data + ")");
console.log(results)
As you can see, the data is my input value returned from ajax request. When using eval(), it can be parsed to 2 array objects.
And now I don't want to use eval() anymore, so I try using JSON.parse(). However, there is an error.
var data = "{listUpdated:[],listConflictOrMerge:[]}"; //returned from Ajax
var results = JSON.parse(data);
console.log(results)
my purpose is that I don't want to use eval() to parse data anymore.
So, is there any ways can do that?.
I try using JSON, but I got unlucky. Am I wrong somewhere?
The data you're trying to parse isn't valid JSON, so JSON.parse can't parse it.
Keys in JSON objects must be quoted, just like any other string. The form you're using is valid in Javascript, but invalid in JSON.
var data = '{"listUpdated":[],"listConflictOrMerge":[]}';
var results =JSON.parse(data);
console.log(results)
I have a JSON file with a lot of content and I load it with the fs Node.js module. But when I look in the JSON file I noticed there is a string of characters attached to many of the field names that make it impossible to target in JS. It looks something like this:
"bk:ParentField": {
"bk:Field": "Value",
"bk:Field2": "Value2"
}
I want to remove the bk: part because I am unable to target the objects with them in it. My code looks like this :
var contents = fs.readFileSync("results.json");
var jsonContent = JSON.parse(JSON.stringify(contents).replace(/bk:/g, '' ));
The problem that whenever I try to target an item after running the code above, I get an error saying an undefined or if I do something like jsonContent['bk:ParentField'] I still get an undefined error.
Any ideas on why this would happen? Or is there a workaround to targeting the objects with the 'bk:'?
The function readFileSync returns a buffer if an encoding is not provided and JSON.stringify takes an Object not a string or buffer.
Just call toString() on the contents buffer before using replace() and then use JSON.parse to create a JavaScript Object:
fs = require('fs');
var contents = fs.readFileSync("test.json");
var data = JSON.parse(contents.toString().replace(/bk:/g, ''));
Or provide an encoding:
fs = require('fs');
var contents = fs.readFileSync("test.json", "utf-8");
var data = JSON.parse(contents.replace(/bk:/g, ''));
Both methods yield the expected result and allow properties to accessed with the . operator:
console.log(data.ParentField.Field);
The replace is not strictly required if you don't mind accessing properties like so:
var data = JSON.parse(fs.readFileSync("test.json", "utf-8"));
console.log(data["bk:ParentField"]["bk:Field"])
It seems that your problem is not the : in the object keys, but the fact that there are no enclosing {} in your JSON string, which makes it invalid. See this example:
var parsed = JSON.parse(`{
"bk:ParentField": {
"bk:Field": "Value",
"bk:Field2": "Value2"
}
}`)
console.log(parsed['bk:ParentField'])
When we can read a property directly from string:
var data = {"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}};
console.log(data.address.streetName); // cde
Why do people use JSON.parse:
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
It is not a string, but Javascript object. String is given below
var data = '{"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}}';
to make it object we use JSON.parse
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
In your first example, data is an object, but in your second example, data is a JSON string.
That's a major difference. You could call eval(data) to parse a JSON string, but that's very unsafe.
JSON.parse() expects a string. More specifically, a string with a JSON-encoded piece of data.
If it's applied to an object then it's an error, the source of which is probably the common confusion that seems to exist between JavaScript objects and the JSON format.