How to interpret JSON field with '-' in node.js - javascript

I am using the node.js to interpret a JSON data, the data format is like this below
{
"href": "https://localhost/light/0000293D",
"i-object-metadata": [
{
"rel": "temperature",
"val": "244"
}
]
}
I can print the raw data using print (body)
to interpret data all works except printing the field i-object-metadata
var obj = JSON.parse(body);
console.log(obj.items); // works well
console.log(obj.i-object-metadata); // error
How could I interpret the JSON object like this i-object-metadata

Can't use the object shorthand in this case, you'll have to use the array notation:
console.log(obj['i-object-metadata'].val); // 244

Related

Create and Read JSON file

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

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

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.

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.

Categories