Error Reading JSON from namespace which contains alphanumeric - javascript

i have a JSON js obejct in
res.metrics.load.1-min
the problem is that this is coming from the server.
i cannot extract anything as it gives illegal number
since res.metrics.load.1-min contains 1-min
Any suggestion i can i parse my JSON. my JSON is an Array
"metrics" : {
"load" : {
"1-min" : [
[
5.87,
1437031875
],
[
5.87,
1437031890
]
]}}
Please help i am using
res.metrics.load.1-min = res.metrics.load.1-min.map(
function (map)
{
return { x: map[1], y: map[0] };
});
to map values to x and y. its throwing an error.

You need to update
res.metrics.load.1-min
to
res.metrics.load["1-min"]

Related

Extracting JSON value in Javascript with special character \"

How can i extract text from the below json, As it contains \" it is giving me an undefined
{
"answers":[
{
"questions":[ ],
"answer":"{\"text\":\"I am Ellina. I can't believe you forgot my name\",\"speech\":\"I am Ellina. I can't believe you forgot my name\"}",
"score":100,
"id":106,
"source":"Editorial",
"metadata":[
],
"context":{
"isContextOnly":false,
"prompts":[
]
}
}
],
"debugInfo":null,
"activeLearningEnabled":false
}
i tried using console.log(Answer:
${JSON.stringify(res.data.answers[0].answer.text)}); and also
console.log(Answer: ${res.data.answers[0].answer.text});
The value of answer is a string.
It isn't an object so it doesn't have a text property (which is why it is undefined).
It appears to be JSON, so you can parse it:
const answer = JSON.parse(es.data.answers[0].answer);
const text = answer.text;
Note that having a JSON text where one of the values in it is a string representation of another JSON text is a good sign of really bad data format design.
Changing the API so it returns answer as an object instead of a JSON representation of an object would be a better approach.
You will have to do the following -
let parsed = JSON.parse(input.answers[0].answer);
where input is the json given by you. Also if you have a long list and you want the json to be parsed automatically then you can do something like this -
input.answers = input.answers.map((answer)=>{
answer.answer = JSON.parse(answer.answer);
return answer;
})
The above code will automatically turn your json string to a parsed JSON.
let input = {
"answers": [{
"questions": [],
"answer": "{\"text\":\"I am Ellina. I can't believe you forgot my name\",\"speech\":\"I am Ellina. I can't believe you forgot my name\"}",
"score": 100,
"id": 106,
"source": "Editorial",
"metadata": [
],
"context": {
"isContextOnly": false,
"prompts": [
]
}
}],
"debugInfo": null,
"activeLearningEnabled": false
}
console.log(input);
input.answers = input.answers.map((answer) => {
answer.answer = JSON.parse(answer.answer);
return answer;
});
console.log(input);

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'.

Cant access data from json

I'm having trouble with JSON. I made this in PHP and I'm sending it to my JavaScript, but I can't get the values.
[
{
"book":[
{
"dir":"extract\/pg1065.epub"
},
{
"dir":"extract\/pg1065.epub\/1065\/0.css"
},
{
"dir":"extract\/pg1065.epub\/1065\/1.css"
},
}
{
"book":[
{
"dir":"extract\/pg6130-images.epub"
},
{
"dir":"extract\/pg6130-images.epub\/6130\/0.css"
},
}
]
I'm trying to access it with
var obj = JSON.parse(result);
alert(obj.book[0].dir[1]);
Anyone have any ideas?
First you need to validate your json, i have validate your json it gives error.
In your json dIr is id.
You have defined 3 dir id for same object this may be error.
EDIT: I missed it but first comment explains your missing your closing square brackets for the book arrays. Add that in and your good to go. Validate the JSON first.
You don't need to do JSON.parse you can simply do
var data = <?php echo "Your generated JSON code"; ?>;
Worth a note you can create your data structure in PHP and then simply use json_encode, then you can be sure it will be valid JSON
var data = <?php echo json_encode($yourData); ?>;
You have output an array so to get the first object you will do something like
var firstObj = data[0];
To get the first dir of the first book
var firstDir = data[0]["book"][0]["dir"];
[
{
"book": [
{
"dir": "extract/pg6130-images.epub"
},
{
"dir": "extract/pg6130-images.epub/6130/0.css"
}
]
},
{
"book2": [
{
"dir": "extract/pg6130-images.epub"
},
{
"dir": "extract/pg6130-images.epub/6130/0.css"
}
]
}
]
Your JSON was not valid i used: http://jsonlint.com/ to sort it!
Now you should be able to acess the data fine.
The code shown in the question is not a valid JSON. There are missing closing square brackets for each of the book arrays and (thanks to #punund) a missing comma between array members. The correct JSON would be this:
[
{
"book":[
{
"dir":"extract\/pg1065.epub"
},
{
"dir":"extract\/pg1065.epub\/1065\/0.css"
},
{
"dir":"extract\/pg1065.epub\/1065\/1.css"
}
]
},
{
"book":[
{
"dir":"extract\/pg6130-images.epub"
},
{
"dir":"extract\/pg6130-images.epub\/6130\/0.css"
}
]
}
]
You should not normally be printing JSON directly, but instead creating a JSON object in PHP and then using json_encode function. The following PHP will produce valid JSON for your scenario:
<?php
$result = array(
(object)array("book" => array((object)array("dir" => "extract/pg1065.epub"),
(object)array("dir" => "extract/pg1065.epub/1065/0.css"),
(object)array("dir" => "extract/pg1065.epub/1065/1.css"))),
(object)array("book" => array((object)array("dir" => "extract/pg6130-images.epub"),
(object)array("dir" => "extract/pg6130-images.epub/6130/0.css")))
);
echo json_encode($result);
?>

Ruby - parsing JSON coming via URL

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.

Accessing Global object of an object in Javascript function

I have a global object abc with the following structure
abc = {
dir_content: {
dir: [
"hi"
]
files: [
"1.txt",
"2.txt"
]
}
directory: "greeting"
}
hope I got the notations correct.
dir_content has its values passed from a JSON object by abc.dir_content = data;
I have a function as below
function show_dir() {
console.log(abc.dir_content.dir);
console.log(abc.directory);
}
I am expecting console.log(abc.dir_content.dir) to show hi. But its saying its undefined instead. console.log(abc.directory) shows greeting just fine.
Adding: I can print the correct results in the console with console.log(abc.dir_content.dir) . But it says undefined when called in the function.
I need to loop through the arrays of dir and files in the function. But now I stuck at getting js to read the values in the function.
Edit: I found something wrong this my global object declaration. fiddle link http://jsfiddle.net/xh5YH/ . Whats wrong with the anonymous function declaration?
abc = {
dir_content: {
// array of one dir
dir: [ "hi" ],
// array of two files
files: [
"1.txt",
"2.txt"
]
},
directory: "greeting"
}
dir_content: {
dir: {
key: "hi"
},
files: {
key1: "1.txt",
key2: "2.txt"
}
}
Notice the difference between [], () and {}
[] means you are creating an array, but you need an Object, hence the {} brackets.
Also, the returned dir_content is not structured correctly. An Object is always structured like this:
{ key: 'content' }
That is why I've added key, key1 and key 2 to the returned data. If you manage to structure the data correctly, everything will work.

Categories