quick question about JSON new line to javascript - javascript

Basically I have a JSON file and whenever I take it to my js application and print it to the console it never print a new line I have no Idea why
my JSON file:
[
{
"id": "71046",
"question": "What is a cpu?",
"answer": "Brain of the computer, it has all the circuity needed to proccess input, store data and output results.",
"options": [""]
},
{
"id": "63888",
"question": "What can the proccessor perform?",
"answer": "1) Basic arithmetic 2) Logic Control 3) Input/Output",
"options": []
},
{
"id": "5418",
"question": "CPU principle components:",
"answer": "1) ALU (Arithmetic Logic Unit)\n 2) Processor Register\\n 3) Control Unit",
"options": []
}
]
I tried many solution to parse print and others and didn't work which is weird
I went through this link in stackoverflow and didn't find solution: How do I handle newlines in JSON?
Here what happens when I stringify (the \n or \n doesn't take it to another line):

That's probably because you don't "print JSON", but "print a JS object"
Basically, what you would get if the console would be in a browser and not in nodejs is
To print JSON as JSON you must convert it back to text with JSON.stringify
JSON.stringify(
{
"id": "71046",
"question": "What is a cpu?",
"answer": "Brain of the computer, it has all the circuity needed to proccess input, store data and output results.",
"options": [""]
}
),
/*replacer(advanced)*/
undefined,
/*indent as <string> of spaces <number>*/
2
)

Each valid JSON is a valid JS
What you are trying to get is
let j = "multiline
string"
which is obviously invalid in JS or JSON
This is caused by JSON stringifying strings.
Stringified strings can't contain newline, JSON allows newlines
For example:
const str = `
- multiline
- string
`
const json = JSON.stringify(str)
// expected = '" \n- multiline \n- string \n"' - no newli
const expected = '"\\n- multiline\\n- string\\n"'
console.log(json == expected)
console.log(json.includes('\n')) // false, does not contain newlines
try {
console.log(JSON.parse('"asi\nzxc"'))
} catch(err) {
/**
* Unexpected token
* in JSON at position 4
*/
console.log(err)
}
/**
* {
* "json": "\"\\n- multiline\\n- string\\n\""
* }
*/
console.log({json})
JSON.stringify(str)

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);

CSV as a signle line string with newlines

I have an existing service to create files from strings and zip them up. It currently takes takes JSON as a string as such:
data: ${ JSON.stringify(data) }
which works. However I want to in the came way express that data as a csv.
assume the data is:
json
[
{
"test1": "1",
"test2": "2",
"test3": "3",
},
{
"test1": "1",
"test2": "2",
"test3": "3",
},
]
I have found many good node json to csv libraries, I ended up using json2csv and have found that I can successfully create a csv file for one line of data, but not two as follows.
// works (header row)
const test = "\"test1\",\"test2\",\"test3\"";
const csvStr = `data:text/csv;charset=UTF-8, ${ test }`;
// fails (header row + 1 data row)
const test = "\"test1\",\"test2\",\"test3\"\n\"test1\",\"test2\",\"test3\"";
const csvStr = `data:text/csv;charset=UTF-8, ${ test }`;
Based on these tests I believe the issue is with how the newline / carriage return is being used. If this is even possible. Anyone know what I might be doing wrong here? If it's possible to express a CSV file on a single line with line breaks?

JSON, node.js: access classes via its name (String)

Here's my situation, I have a JSON that looks somewhat like this:
{
"items": [{
"type": "condition",
"data": {
"type": "comparison",
"value1": {
"source": "MyType1",
"component": "Attribute1"
},
"value2": {
"source": "MyType2",
"component": "Attribute2"
},
"operator": "gt"
}
},
{
"type": "then",
"data": {
"result": "failed",
"message": "value1 is too high"
}
}
]
}
and would want it to translate to:
if (MyType1.Attribute1 > MyType2.Attribute2) {
result = "failed";
console.log("value1 is too high");
}
Now my problem is, I don't know how I would translate the entries of value1 and value2 to actual code, or rather, how I could access the Object MyType1(maybe through something like getAttribute("MyType1")).
Since I am going to have a whole bunch of sources which each have different components, I cant really write a huge dictionary. Or I would like to avoid it.
The goal is to allow creating if - then - statements via some interactive UI, and I figured it'd be best to save that code as .json files. (Think rule management system).
So, TL,DR, How would I access a Class Attribute this.MyType, if I only have a String MyType to go from? And how would I access the value this.MyType.MyValue, if I get another String MyValue?
Thanks in advance.
Edit:
I'd really like to avoid using eval, for obvious reasons. And if I have to - I guess I would need to create Dictionaries for possible JSON Values, to validate the input?
You need some kind of parser. At first we need some way to store variables and maybe flags:
const variables = {};
var in = false;
Then we go through the code and execute it:
for(const command of items){
switch( command.type ){
case "condition":
//...
case "then":
//...
}
}
To access a variable we can simply do
var current = variables[ identifier ];
To store its the other way round:
variables[ identifier ] = current;

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