Extracting JSON value in Javascript with special character \" - javascript

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

Related

quick question about JSON new line to 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)

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 interpret JSON field with '-' in node.js

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

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