Need to parse JSON string with value is quoted curly braces - javascript

I need to parse JSON string.
I've tried JSON.stringify and then JSON.parse below sample string, but server performed escape sequencing
I used str.replace('/\\/g','') to remove the escape sequence but that doesnt help because if you look in the "default_request" key is wraps its value with "" which is doesnt allow me parse it using JSON.parse()
{
"request": {
"service_name": "authService",
"url": "https://some-url.com/{accounts}",
"default_request": "{\"authMethod\":\"somename\",\"multiCheck\":false}"
}
}
so I tried to replace "{ with { and }" with }
str.replace('/"{/g','{')).replace('/}"/g','}'))
but it creates another problem.
Favourable condition
{
"request": {
"service_name": "authService",
"url": "https://some-url.com/{accounts}",
"default_request": {\"authMethod\":\"somename\",\"multiCheck\":false}
}
}

default_request was stringifyied twice. to fix it, try this
jsonObject.request.default_request = JSON.parse(jsonObject.request.default_request);

Related

Accessing JSON data with colon in the label

I have json data with a colon in the label (see responsedata) which I'm finding difficult to access in Angular with the following code:
<li ng-repeat="i in items.autnresponse.responsedata | searchFor:searchString"> <p>{{i.autn:numhits}}</p> </li>
I keep getting an error like this:
Error: [$parse:syntax] Syntax Error: Token ':' is an unexpected token at column 7 of the expression [i.autn:numhits] starting at [:numhits].
JSON data excerpt:
"autnresponse": {
"action": {
"$": "QUERY"
},
"response": {
"$": "SUCCESS"
},
"responsedata": {
"autn:numhits": {
"$": "92"
},
"autn:totalhits": {
"$": "92"
},
"autn:totaldbdocs": {
"$": "188"
},
"autn:totaldbsecs": {
"$": "188"
},
Does anybody know a way around this?
I'll assume I know the answer to my question from the comments and post what would be my response:
Assumption
Your JSON parses fine but your code can't access something in the resulting data structure
Answer
Use square bracket notation with a string:
var x = i['autn:numhits'];
The same can be used when you have a property name in a variable. Using your same example:
var propertyName = 'autn:numhits';
var x = i[propertyName];
Addendum
For Angular template, try
{{i['autn:numhits']}}
Use brackets to access it like a dictionary rather than dot notation. Replace {{i.autn:numhits}} with {{i['autn:numhits']}}
As a heads up, if you want to wrap autn:numhits with double quotes you will need to html escape them.

JSON Stringify Ouput to Multiple Lines

I'm writing a simple JS app that takes in a JSON file, displays the information to the user and allows them to modify it, and then allows them to re-export the JSON. However, the JSON that is being brought in is multi-line; each key/value is on its own line. When I use .stringify to output the JSON, it all appears on one line. Is there any way for the stringify method to separate the lines?
JSON Structure:
{"Title":
{"lvlOne":[
{"key":"val"},
{"key":"val"},
{"key":"val"}
],
"lvl2":[
{"key":"val"},
{"key":"val"},
{"key":"val"}
]}
}
But when I output, it all shows:
{"Title":{"lvlOne":[{"key":"val"},{"key":"val"},{"key":"val"}],"lvl2":[{"key":"val"{"key":"val"},{"key":"val"}]}}
You can use the space parameter of the stringify method. From the official page, here is the relevant excerpt:
JSON.stringify({ a: 2 }, null, " "); // '{\n "a": 2\n}'
you can also use.
var json = JSON.stringify({ uno: 1, dos : {"s":"dd","t":"tt"} }, null, '\t');
console.log(json);
Or even better, the count of spaces in the indentation:
var json = JSON.stringify({ uno: 1, dos : {"s":"dd","t":"tt"} }, null, 2);
None of the above worked for me the only thing that worked for me was
await fs.promises.writeFile('testdataattr.json',JSON.stringify(datatofile, null,'\r\n'),'utf8') ;

Use javascript variable instead json file

here I have a declaration:
<div id="timeline-embed"></div>
<script type="text/javascript">
var timeline_config = {
width: "100%",
height: "100%",
debug: true,
rows: 2,
source: 'Timeline/example_json.json'
}
</script>
<script type="text/javascript" src="Timeline/compiled/js/storyjs-embed.js"></script>
so now I want to instead source: 'Timeline/example_json.json' to use
something like:
source: '{
"timeline":
{
"headline":"Sh*t People Say",
"type":"default",
"text":"People say stuff",
"startDate":"10/4/2011 15:02:00",
"date": [
{
"startDate":"10/4/2011 15:10:00",
"endDate":"10/4/2011 15:55:00",
"headline":"prvo",
"text":"<p>dddddddddddddddd dd</p>",
"asset":
{
"caption":"yessss"
}
},
{
"startDate":"10/4/2011 17:02:00",
"endDate":"10/4/2011 18:02:00",
"headline":"drugo da da",
"text":"<p>In true political fashion, his character rattles off common jargon heard from people running for office.</p>",
"asset":
{
"media":"http://youtu.be/u4XpeU9erbg",
"credit":"",
"caption":""
}
}
]
}
}'
but doesn work. I really dont know what is probem exactly... Please help.
So this is verite Timeline plugin and this plugin need JSON as source, but is there any way to change source with Javascript variable?
The way you have this written, the value of "timeline_config.source" is a String, not a "usable" Javascript object.
You may need to convert the string to an object using JSON.parse(). So add this line of code as the last line of your first < script > block.
timeline_config.source = JSON.parse(timeline_config.source)
Alternatively, as pointed out in the comments, you can simply remove the single quotes around the string, and it will natively by a JS Object.
Try removing the ' string delimiter, so it says
source: {
"timeline": { ... }
},
This way it is a JS object and not a string.

How do I access JSON elements through javascript?

The JSON file I have is following:
{
"root": {
"Quizsize": null,
"{urn:abc.com/xmlns/mona/page}page": [
{
"#xid": "page1623",
"#title": "Quiz Landing Page",
"{urn:abc.com/xmlns/mona/page}comment": null,
"{urn:abc.com/xmlns/mona/page}skills": null,
"{urn:abc.com/xmlns/mona/page}info": {
"{urn:abc.com/xmlns/mona/common}property": {
"#name": "quiz_landing",
"#value": "true"
}
}
}
]
}
}
}
I am loading this JSON file using :
var jsondata = eval("("+chapterRequest.responseText+")") ;
Root = jsondata.root
Now I want to access #xid which is "page1623 and #name which is "quiz_landing". I dont know how to do this,Please help.
Thanks
JSON.parse(x) is better than eval(x), for one. It is not supported natively by some browsers though. If you want to access #xid, "urn:abc.com/xmlns/mona/page}page" points to an array whose first element is an object.
So use Root["{urn:abc.com/xmlns/mona/page}page"][0]["#xid"]. Or mix bracket and dot notation. Your choice, really.
When the key isn't a valid identifier, you use object['key'] instead of object.key, so jsondata.root['{urn:abc.com/xmlns/mona/page}page'][0]['#xid'].

how to display escape sequences in JSON in Java script text box

I am sending a JSON object from a servlet to JSP using AJAX. My JSON object contains a String value inside. and that string contains double quotes within that. My JSON does not parse it. I get the following error:
{"diagnosis":[{"NAME":"new_diagnosis_1 \[1020\]:2000000006001"},{"NAME":"new_diagnosis_2 \[1021\]:2000000006003"},{"NAME":"new_"dise"sed \[1023\]:2000000009001"},{"NAME":"new_d"ise"sef \[1024\]:2000000009003"}]}
note new_"dise"sed and new_d"ise"sef
I need a solution.
your json is not valid
try this
{
"diagnosis": [
{
"NAME": "new_diagnosis_1 [1020]:2000000006001"
},
{
"NAME": "new_diagnosis_2 [1021]:2000000006003"
},
{
"NAME": "new_\"dise\"sed [1023]:2000000009001"
},
{
"NAME": "new_d\"ise\"sef [1024]:2000000009003"
}
]
}
use \ to escape quotes
you can validate your json here
http://www.jsonlint.com/

Categories

Resources