I created a JSON file as follows
{
"fooditems" : [
{
"name": "pizza",
"type": "fastfood",
"price": 10
},
{
"name": "apple",
"type": "fruit",
"price": 1
}
]
}
created a JS file to read the JSON file
const data = require("./data.json");
data1 = JSON.parse(data);
data1.foodData.forEach( foodItem => console.log(foodItem));
When I run the JS, I get error for the json file
Syntax error: Unexpected token o in json at position 1
at JSON.parse
You don't need to parse data since it's already and object. The following should work.
const data = require("./data.json");
data.fooditems.forEach( foodItem => console.log(foodItem));
Note foodData was change to fooditems based on the contents of the data.json file.
Your initial data JSON contains "fooditems", but in the JS file you are trying to process the "foodData". Change the "foodData" to "fooditems" and it should work.
I think that you are trying to access invalid object key in your JS file on the last line.
Instead of
data1.foodData
put
data1.fooditems
How to convert html data attribute into JavaScript Object?
I try to use JSON.parse() but it got some error
There is result of my String Data
{
_id: 5f71ea3362749a305427a012,
name: 'House With Beauty Backyard',
__v: 0
}
When i use JSON.parse() it return error
VM5246:2 Uncaught SyntaxError: Unexpected token _ in JSON at position 4
My EJS Code
<i class="fas fa-edit"></i>
My JS Code
<script>
$('#dataTable .btn-update').on('click', function () {
let dataString = $(this).data('category');
console.log(dataString);
let dataJson = JSON.parse(dataString);
console.log(dataJson);
$('#update-modal').modal('show');
})
</script>
Use JSON.stringify. Try this code:
let dataJson = JSON.parse(JSON.stringify(dataString));
console.log(dataJson);
JSON requires quotes ("") for keys and string values.
This would be your "String Data" with valid form:
{
"_id": "5f71ea3362749a305427a012",
"name": "House With Beauty Backyard",
"__v": 0
}
The parsing error will disappear, if you change your data format to valid JSON.(RFC 8259)
Here you can find out more about JSON:
https://tools.ietf.org/pdf/rfc8259.pdf
I have this method
function submit() {
var JSONObject = {
"name":$rootScope.name,
"surname":$rootScope.surname,
"email":$rootScope.email,
"review":$rootScope.review
};
debugger;
var Results = UniversalService.PostReview(JSONObject);
}
which I want to post to database later and I get error: SyntaxError: Unexpected token o in JSON at position 0
As I understood I get incorrect JSON format as my console.log input shows :
Object {name: "hh", surname: "hh", email: "kal#gmail.com", review: "fre"}
Instead it should show : "name": "hh" info like this right? How do I change that?
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.
Ive changed a json object recieved from an api and changed it to an array using $.makeArray and now im struggling to get values from this array. Im wanting temp_c and value within weather desc. A print out of the array is below.
[
Object
data: Object
current_condition: Array[1]
0: Object
cloudcover: "50"
humidity: "72"
observation_time: "10:25 AM"
precipMM: "0.1"
pressure: "1005"
temp_C: "13"
temp_F: "55"
visibility: "10"
weatherCode: "122"
weatherDesc: Array[1]
0: Object
value: "Overcast"
__proto__: Object
length: 1
__proto__: Array[0]
weatherIconUrl: Array[1]
winddir16Point: "SSW"
winddirDegree: "210"
windspeedKmph: "19"
windspeedMiles: "12"
__proto__: Object
length: 1
__proto__: Array[0]
request: Array[1]
__proto__: Object
__proto__: Object
You could try:
alert(yourObject.temp_C);
And
alert(yourObject.weatherDesc.value);
You wouldn't need to convert it to an array :)
You don't need to transform the object into an array, just access the properties you need:
var o = object_retrieved_from_api;
o.temp_c;
o.weatherDesc[0].value;
If you convert it into an array, just have to index first object in array:
var a = $.makeArray(object_retrieved_from_api);
a[0].temp_c;
a[0].weatherDesc[0].value;
The whole point of JSON is that it is already a Javascript object, so you don't need any complex parsing logic in order to get the data out. Try out the following code and you'll see how easy it is to get data from a JSON web service.
$.getJSON('your JSON URL here', function(data) {
$.each(data.current_condition, function() {
alert(this.temp_C + "C " + this.weatherDesc[0].value);
});
});