Ruby - parsing JSON coming via URL - javascript

I'm sending a JSON object to ruby with javascript. But I cannot parse it in there. I tried following stuff but no luck. Also I've been searching around for while now, but I couldn't find anything helpful.
Note that I'm very new ruby.
My trials:
def initialize(game_conf_json)
parsed_conf = JSON.parse(conf_json)
#param1 = parsed_conf['name'][0]
#param2 = parsed_conf['surname'][0]
=begin
I also tried this:
#param1 = parsed_conf['name']
#param2 = parsed_conf['surname']
But no matter what other things I try, I'm getting the following error:
"21:in `[]': can't convert String into Integer (TypeError)"
OR
"can't convert Array into String (TypeError), "
=end
File.open("some_direc/conf.json", "w") do |f|
f.write(game_conf_json)
end
end
I create the json in javascript like this:
var json_of_form_vars = {};
json_of_form_vars.name = name_val;
json_of_form_vars.surname = surname_val;
And send it this way:
$.ajax({
url: "../fundament/dispatch.rb/",
type: "post",
dataType: "json",
data: "conf="+json_of_form_vars,
.....
How can I solve this problem? Is there any proper tutorial for this of problem?
UPDATE1 (After suggestions):
I used JSON.stringify and then passed the object to ruby. And then I finally able to print the object in ruby. It's listed below:
{"name": "METIN", "surname": "EMENULLAHI"}
The method .class claims that it is an array. But I cannot access data with classical ways, like:
array['name']
the error is:
can't convert String into Integer
And when I try to pass it to the JSON.parse in ruby, it gives me the following error:
can't convert Array into String
So I used JSON.parse(conf_array.to_json), but again when accessing the data it gives the same error like arrays:
can't convert String into Integer
What should be done now?
UPDATE2
Here is my cgi handler which passes the URL parameters to appropriate places:
cgi_req = CGI::new
puts cgi_req.header
params_from_request = cgi_req.params
logger.error "#{params_from_request}"
action_todo = params_from_request['action'][0].chomp
base = Base.new
if action_todo.eql?('create')
conf_json = params_from_request['conf']
# This line prints the json like this: {"name": "SOME_NAME", "surname": "SOME_SURNAME"}
logger.error "#{conf_json}"
base.create_ident(conf_json)
end
And in Base class:
def create_ident(conf_json)
require 'src/IdentityCreation'
iden_create = IdentityCreation.new(conf_json)
end
IdentityCreation's constructor is listed above.
UPDATE3:
Ok, I now get at least something out of the array. But when I access a key, it displays the key itself:
parsed_conf = JSON.parse(conf_json.to_json)
#param1 = parsed_conf[0]['name']
#param2 = parsed_conf[0]['surname']
# At this point when I print the #param1, it gives me "name"(the key), not "SOME_NAME"(the value).

Here an example of parsing a JSON string. If you still have problems, publish the generated JSON so that we can try it.
require 'json'
require 'ap'
string = %{
{"configurations" : [
{ "drinks" : [
{"menus" : [
{ "hot" : [
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 4},
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 6}
] },
{ "cold" : [
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 4},
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 6}
] },
{ "terminals" : { "id" : 4, "id": 6, "id": 7 } },
{ "keys" : { "debit" : "on", "credit": "off" } }
] }
] } ] }
}
hash = JSON.parse(string)
ap hash
gives
{
"configurations" => [
[0] {
"drinks" => [
[0] {
"menus" => [
[0] {
"hot" => [
[0] {
"id" => 15,
"unit" => "0.33",
"price" => "1",
"currency" => "Euro",
"position" => 4
},
etc..

At the moment you're not actually posting json. You're attemping to post json wrapped inside form encoded parameters. In addition, when you do
"conf=" + json_of_form_vars
javascript will convert json_of_form_vars to a string for you but that conversion isn't the same as dumping to JSON. Javascript default string conversions are pretty useless for objects, so you'll need to use JSON.stringify to get actual json.
Since you're composing the body as a string literal you'll also need to escape any special characters that aren't allowed (or have special meaning) in this context. It's usually easier to let jquery do the heavy lifting, with something like
$.ajax({
url: "../fundament/dispatch.rb/",
type: "post",
dataType: "json",
data: {conf: JSON.stringify(json_of_form_vars)}

I solved it finally. Using all the suggestions made under this post and also my irb experiences with hashes, arrays, json and etc.
So instead of converting my object (conf_json) to json (with to_json), I passed it to JSON.parse as a string like below:
parsed_conf = JSON.parse(%{#{conf_json}})
It seems kind of weird to me, because when try to pass it to function like below, I got the error of can't convert Array into String.
parsed_conf = JSON.parse(conf_json)
But it is working like a charm right now.

Related

convert a string containing JavaScript object to a JSON string with PHP

This is the javascript Object (just a small part of it):
dataToReturn = {
"dimensionsDisplayType" : [
"dropdown","swatch",
],
"pwEnabledDimensionMap" : {
"size_name": true,
"color_name": true
},
"isPWBadgeEnabled" : true,
"isImmersiveExperience" : false,
"isTabletWeb" : false
}
So in PHP it will look like:
<?php
$jsObjStr = '{
"dimensionsDisplayType" : [
"dropdown","swatch",
],
"pwEnabledDimensionMap" : {
"size_name": true,
"color_name": true
},
"isPWBadgeEnabled" : true,
"isImmersiveExperience" : false,
"isTabletWeb" : false
}';
But if we would like to parse it with json parse we cant In PHP since its not a clean JSON format because of
"dimensionsDisplayType" : [
"dropdown","swatch",
]
The keys containing object like "dimensionsDisplayType" can be unpredictable so cleaning with regex for example wont help much.
The one that works is
JSON.stringify(dataToReturn)
But in my case I can not run client side code sot it must be converted into the correct JSON format in server side with PHP. I was searching a lot online but I got not any satisfying function or library.
How can this be solved ?
You could try cleaning the string with this regex, this will look for a comma followed by optional whitespace and a close ] and replace this with the content minus the comma...
$jsObjStr = preg_replace("/,(\s*?])/", "$1", $jsObjStr);

Properly parse CSV file to JSON file in JavaScript

I have a CSV file and I want to parse it using PapaParse. How do I do this properly?
I have so far:
Papa.parse(fileInput, {
download: true,
complete: function(results) {
console.log(results.data);
console.log(results.errors);
}
});
However, is there a better way to do this? Is this the proper way to get errors? The documentation didn't emphasize download: true or anything so I was wondering if there are any experts on this subject here.
EDIT: Also, am I suppose to further parse the file with papacsv or do it in react. For instance, if I have multiple arrays in my data file which have a similar name reference. Should I initially somehow parse the file so it groups all those references together and how would I go about doing this?
For instance,
Date, Name , Win/Lose
I want to group all the winners together. How do I do that?
The method you are using of Papa parse, is for remote CSV.
download: true is for downloading the remote file.
By using Papa parse, this is the only way of getting errors, data, meta with parse result object.
//If(header:true)
var data = [
{
"date": "8/12/2018",
"name": "foo",
"win/loose": "win"
},
{
"date": "8/12/2018",
"name": "foo",
"win/loose": "loose"
},
{
"date": "8/12/2018",
"name": "foo1",
"win/loose": "win"
},
];
var winners = data.filter(d => d['win/loose'] == 'win');
console.log(winners);
//If you want to group winners and losers then:
var grouped = data.reduce(function(acc, co) {
var key = co['win/loose'];
if(!acc[key]) {
acc[key] = [];
}
acc[key].push(co);
return acc;
}, {});
console.log(grouped);
This'll give you separate array of winners from extracted data.

How to add a json object to a json array in an external file in javascript / capserjs

I am writing to a json file in casperjs and am trying to add new objects to it.
json file looks like
{ "visited": [
{
"id": "258b5ee8-9538-4480-8109-58afe741dc2f",
"url": "https://................"
},
{
"id": "5304de97-a970-48f2-9d3b-a750bad5416c",
"url": "https://.............."
},
{
"id": "0fc7a072-7e94-46d6-b38c-9c7aedbdaded",
"url": "https://................."
}]}
The code to add to the array is
var data;
if (fs.isFile(FILENAME)) {
data = fs.read(FILENAME);
} else {
data = JSON.stringify({ 'visited': [] });
}
var json = JSON.parse(data);
json.visited.push(visiteddata);
data = JSON.stringify(json, null, '\n');
fs.write(FILENAME, data, "a");
This is starting off by adding an new { "visited" : [ ] } array with first couple of objects, below the existing { "visited" : [ ] } array and subsequently the script breaks because the json array is no longer valid json.
Can anybody point me in the right direction. Thank you in advance.
You have a JSON file containing some data.
You:
Read that data
Modify that data
Append the modified version of that data to the original file
This means the file now has the original data and then, immediately after it, a near identical copy with a little bit added.
You don't need the original. You only need the new version.
You need to write to the file instead of appending to it.
Change the 'a' flag to 'w'.

How to add text to beginning and ending of JSON to make it JSONP

I'm working on a project, I can manually add a beginning name and parenthesis: bio(
and an ending ) to the end of my JSON data to make it callable as JSONP.
I am going to do this to about 200 files which is why I'm trying to find a solution to do this in code.
I've tried using regex, converting to a string, trying to convert back, etc, and nothing seems to work.
My abbreviated JSON data is below:
{
"Directory": {
"workbooks": ["/xl/workbook.xml"],
"sheets": ["/xl/worksheets/sheet1.xml"],
"style": "/xl/styles.xml",
"defaults": {
"xml": "application/xml",
"rels": "application/vnd.openxmlformats-package.relationships+xml"
}
},
"Workbook": {
"AppVersion": [null],
"Sheets": [
[null]
],
"CalcPr": [null],
"xmlns": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
}
What I want is:
bio({ <--------
"Directory": {
"workbooks": ["/xl/workbook.xml"],
"sheets": ["/xl/worksheets/sheet1.xml"],
"style": "/xl/styles.xml",
"defaults": {
"xml": "application/xml",
"rels": "application/vnd.openxmlformats-package.relationships+xml"
}
},
"Workbook": {
"AppVersion": [null],
"Sheets": [
[null]
],
"CalcPr": [null],
"xmlns": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
}) <-------
I've gotten closest with Stringify and regex:
var myString = JSON.stringify(workbook);
var change = myString.replace(/^/,"bioInfo(").replace(/$/,")”);
When I try to change it back to an object so I can use it though, it fails saying:
JSON.parse: unexpected character at line 1 column 1 of the JSON data
I've tried eval as well trying to get it to change back to an object but it just doesn't seem to work.
Hopefully my dilemma is clear and someone knows a good way to do this in Javascript or Jquery.
Thanks in advance.
You don't need anything as complicated as you are making it. Just concatenate your strings.
var jsonp = "bio(" + json + ");"
I've gotten closest with Stringify
JSON is already a string. You only need to stringify something if you have a JavaScript data structure and want to convert it to JSON.

How to manipulate JSON object to remove root key within Javascript?

I have a json url that returns data in the format
{
"photos" : [
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
}
I'm using the json in a javascript function, and need to manipulate it to remove the root key. i.e. I want something that looks like
[
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
I've been hacking around with various approaches, and have referred to several similar posts on SO, but nothing seems to work. The following seems like it should.
var url = 'http://path/to/my/json/feed.json';
var jsonSource = $.getJSON( url );
var jsonParsed = $.parseJSON(jsonSource);
var jsonFeed = jsonParsed.photos
What am I doing wrong?
A couple of issues there.
That's invalid JSON, in two different ways. A) The : after "photos" means that it's a property initializer, but it's inside an array ([...]) when it should be inside an object ({...}). B) There are extra " characters in front of the images keys. So the first thing is to fix that.
You're trying to use the return value of $.getJSON as though it were a string containing the JSON text. But $.getJSON returns a jqXHR object. You need to give it a success callback. That callback will be called with an object graph, the JSON is automatically parsed for you.
Assuming the JSON is fixed to look like this:
{
"photos": [
{
"id": 1,
"image": "https://path/to/my/image/1.jpg"
},
{
"id": 2,
"image": "https://path/to/my/image/2.jpg"
}
]
}
Then:
$.getJSON(url, function(data) {
var photos = data.photos;
// `photos` now refers to the array of photos
});

Categories