Parse any json in javascript - javascript

i want to parse any json in javascript (react more exactly) and put it in a big object (to show it on UI and modify before put it again in json)
But i don't know how to exactly do that !
I tried with
var data = require("./test.json");
var jsonString = JSON.stringify(data);
But after that i don't know how to parse correctly my file,i can't name programaticaly my properties in my array so impossible to parse manually..
I precise i don't know json content so i can't do pre-build object.
Thank you for you answers ! :)

Related

Scrapy: Converting Javascript array to Json on Python

I have been struggling with a site I am scrapping using scrappy.
This site, returns a series of Javascript variables (array) with the products data.
Example:
datos[0] = ["12345","3M YELLOW CAT5E CABLE","6.81","1","A","N","N","N","N","N",0,0,0,0,0,"0","0","0","0","0","P","001-0030","12","40K8957","28396","250","Due: 30-12-1899",0.0000,1,"",\'\'];
datos[1] = ["12346","3M GREEN CAT5E CABLE","7.81","1","A","N","N","N","N","N",0,0,0,0,0,"0","0","0","0","0","P","001-0030","12","40K8957","28396","250","Due: 30-12-1899",0.0000,1,"",\'\'];
...
So on...
Fetching the array into a string with scrapy was easy, since the site response prints the variables.
The problem is I want to transform it into Json so I can process it and store it in a database table.
Normally I would use Javascript's function Json.stringify to convert it to Json and post it in PHP.
However when using Python's json.loads and even StringIO I am unable to load the array into json.
Probably is a format error, but I am unable to identify it, since I am not expert in Json nor Python.
EDIT:
I just realize since scrapy is unable to execute Javascript probably the main issue is that the data is just a string. I should format it into a Json format.
Any help is more than welcome.
Thank you.
If you wanted to take an array and create a json object, you could do something like this.
values = ["12345","3M YELLOW CAT5E CABLE","6.81","1","A","N","N","N","N","N",0,0,0,0,0,"0","0","0","0","0","P","001-0030","12","40K8957","28396","250","Due: 30-12-1899",0.0000,1]
keys = [x for x in range(len(values))]
d = dict(zip(keys, values))
x = json.dumps(d)
There is a section in the scrapy doc to find various ways to parse the JavaScript code. For your case, if you just need to have it in an array, you can use the regex to get the data.
Since the website you are scraping is not present in the question, I am assuming this would be a more straightforward way to get it, but you could use whichever way seems suitable.

Accessing an array of objects stored in a json file

I am trying to access an array of objects, with javascript, that is stored in a json file on my site. I could just include the array of objects in my js, but I'm trying to learn how to use json files.
I would like to store the array as a variable in my js file. What is the best way to go about this?
You just need to pass the String to:
JSON.parse("{my:'object'}")
To read the file from the server, just use the ajax api.
$.get( "my-endpoint/test.json", function( data ) {
var jsObject = JSON.parse(data)
});
I guess Jquery might already have parsed the data and you do not even need to call JSON.parse() - try it out :)

JS: convert string into object

I have code
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
I want to convert it into JS object (not in JSON) and use it in this way:
data.newFavOfferId = ...
How can I do this?
If your source is trusted, the simplest solution is to use eval :
data = eval('('+data+')');
If you don't trust the source, then you'd better specify what you can have and parse the string manually (not terribly hard if you have only one level of properties for example).
Another solution (depending on your real data) would be to change your data into JSON by inserting the missing quotes :
data = JSON.parse(datareplace(/({|,)\s*([^:,}{]+)\s*(:)/g,'$1"$2"$3'));
just remove the quotes
data = {
isShowLoginPopup:true,
newFavOfferId:1486882
};
Fiddle: http://jsfiddle.net/QpZ4j/
just remove quotes "" from the
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
DEMO
Whilst on the surface this looks like JSON data, it's malformed and therefore it does not work directly with JSON.parse(). This is because JSON objects require keys to be wrapped in quotes...
therefore:
"{isShowLoginPopup:true,newFavOfferId:1486882}"
as valid JSON should be:
"{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}"
So what you have there in fact IS a JavaScript object, not JSON, however the problem you have is that this is a JavaScript object as a string literal. If this is hard coded, then you need to just remove the " from the beginning and end of the string.
var data = {isShowLoginPopup:true,newFavOfferId:1486882};
If this object is serialized and requires transmission from/to a server etc, then realistically, it needs to be transmitted as a JSON formatted string, which can then be de-serialized back into a JavaScript object.
var data = JSON.parse("{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}");

How to create a JSON object in javascript

I am facing an issue with the JSON structure for the data I should pass to the server. Below is the required format.
var data = '{"listingHotspots": [{"PropertyGuid": "5dc934f6-cb5a-44d4-95e6-cf7d5712359e","Hotspot": {"Coordinates": "581,391,676,391,677,410,714,410,715,562,599,562,598,527,597,473,597,409,580,407,581,391"}}]}'
My code is
var data = {'listingHotspots':[]};
data['listingHotspots'].push({'PropertyGuid':savedGuid,'Hotspot': {'Coordinates':coord_string}});
This is creating a valid JavaScript object but not the one i need. I also used JSON.stringify() but it resulted in a Undefined value. Any help would be greatly appreciated.
JSON.stringify() may not be in the target browser. If that's the case, you'll need to load json2.js. json2.js won't clobber the native JSON.stringify() if it exists, so aside from the extra request, no harm loading it all the time. See http://www.json.org/js.html and http://www.cdnjs.com/#/search/json2 and http://modernizr.com/docs/#load

question about JSON

If I have in my db a table called User with name, Id, age fields and I want to get these data and put it in a var as a JSON serialize, then I want to send it to javascript page to reform it as I want . I need to know how to put these data in a var as a JSON, how to read the data in the javascript file (how to deal with each one. for example : array[name]) !!!?
which thing is more better to deal with these data in asp.net code then send it in the javascript or to send it to the javascript and then to deal with !!? thank u :D
If you have an object in .NET you can serialize it using the JavaScriptSerializer
List<User> myUsers = GetAllUsers();
string userJson = new JavaScriptSerializer().Serialize(myUsers);
This way you won't have to worry about escaping quotes or anything. Now that you have a string, you can feed that to your javascript:
var userJson = ... // the JSON string
var myUsers = JSON.parse(userJson);
The other way around, you may have a javascript object, that you want to pass to the server:
var myUsers = ... // a JS object
var userJson = JSON.stringify(myUsers);
If you pass the string userJson to the server, you can then deserialize it. If you know that the JS object corresponds entirely, in terms of property names, to a .NET object, or an array of .NET objects, say, you can deserialize it as such:
List<User> myUsers = new JavaScriptSerializer().Deserialize<List<User>>(userJson);
If there isn't a .NET object that can be directly mapped to the structure of the JS object, you'll have to use
object myUsers = new JavaScriptSerializer().DeserializeObject(userJson);
4guysfromrolla have great articles that will teach you the ins and outs of it.
https://web.archive.org/web/20210927191305/http://www.4guysfromrolla.com/articles/102010-1.aspx
https://web.archive.org/web/20211020203220/https://www.4guysfromrolla.com/articles/040809-1.aspx
you can take a look at these for your complete understanding.
besides if you just want to display results of a query ti the UI then why dont you use the gridview or repeater controls.

Categories

Resources