Working with nested JSON object gives me console error - javascript

Working with a JSON nested object and I get an error when running in the javascript console "JSON3.html:11 Uncaught SyntaxError: Invalid or unexpected token"
I've verified the JSON via https://jsonformatter.org/json-viewer and that looks ok. The output is only the text in my h2 tag. What am I missing?
Here's the code.
<!DOCTYPE html>
<html>
<body>
<h2>Testing JSON .</h2>
<p id="demo"></p>
<script>
var myJSON = '{
"LevelOne": {
"LevelTwo": {
"location": {
"campus": "SouthWest",
"building": "Biggest",
"floor": "1st",
"room": "101"
},
"quantity": "1",
"section": "ABC",
"task": "abc123456zyx"
}
}
}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myJSON.LevelOne.LevelTwo.location;
</script>
</body>
</html>

String concatenation
String that are surrounding using " and ' cannot extend over multiple lines, so have to separate each line and then concatenate them. Example:
var myJSON = '{' +
'"LevelOne": {' +
'"LevelTwo": {' +
'"location": {' +
'"campus": "SouthWest",' +
'"building": "Biggest",' +
'"floor": "1st",' +
'"room": "101"' +
'},' +
'"quantity": "1",' +
'"section": "ABC",' +
'"task": "abc123456zyx"' +
'}' +
'}' +
'}';
console.log(myJSON);
Template Literals
In ES6, template literals were added, that allow to have strings span through multiple lines, provided you use ` instead of " or '. Example:
var myJSON = `{
"LevelOne": {
"LevelTwo": {
"location": {
"campus": "SouthWest",
"building": "Biggest",
"floor": "1st",
"room": "101"
},
"quantity": "1",
"section": "ABC",
"task": "abc123456zyx"
}
}
}`;
console.log(myJSON);
Removes the new lines from the JSON
A simple way to make the JSON 1 line tall is to do JSON.stringify(json) at the browser's console.
Use a normal JSON
You can just use the normal object notation of the JSON instead of the JSON and then if you want to you can convert it back to a string using JSON.stringify. Example:
var myJSON = {
"LevelOne": {
"LevelTwo": {
"location": {
"campus": "SouthWest",
"building": "Biggest",
"floor": "1st",
"room": "101"
},
"quantity": "1",
"section": "ABC",
"task": "abc123456zyx"
}
}
};
console.log(JSON.stringify(myJSON));
console.log(myJSON);

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).Including parsing JSON so you can access data within it, and creating JSON
Instead of using JSON data as a string you can directly add the JSON
data or use the double quote.if you are storing the JSON object of object in a variable using single quote, You just > write add the JSON data string in a single line or else use the double quote.
Example
<!DOCTYPE html>
<html>
<body>
<h2>Testing JSON .</h2>
<p id="demo"></p>
<script>
var myJSON = '{"LevelOne": {"LevelTwo": {"location": { "campus": "SouthWest","building": "Biggest","floor": "1st", "room": "101"},"quantity": "1","section": "ABC","task": "abc123456zyx"}}}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.LevelOne.LevelTwo.location;
</script>
</body>
</html>
You can get the result.!
Another Solution

myJSON.LevelOne.LevelTwo.location is OBJECT
var myJSON =
{ LevelOne:
{ LevelTwo:
{ location:
{ campus: "SouthWest", building: "Biggest", floor: "1st", room: "101"}
, quantity: "1"
, section: "ABC"
, task: "abc123456zyx"
}
}
}
console.log ( myJSON.LevelOne.LevelTwo.location )
// ===> OBJECT

Related

How To Add A String Inside An Object For The Given Example

Hi iam finding the best way to add a string inside the given object.Any help would be appreciated
my String is 'created'
Down Below Is My Data
{
"id": "222",
"list": [
{
"name": "Tony",
}
],
iam trying to insert 'created' in the data like this
{
"id": "222",
"list": [
{
"name": "Tony",
"type":"created"
}
]
The string you've provided looks a lot like JSON data. You can convert a JSON string to an actual javascript object by using the JSON.parse(string) method.
With this object we then can query it's list property - which in your case is an array of objects - and add a new property type to each of the arrays elements. The final step is converting the object back to a JSON string using the JSON.stringify(object) method.
Here's an example:
let str = `{
"id": "222",
"list": [
{
"name": "Tony"
}
]
}`;
let data = JSON.parse(str);
data.list.forEach(element => {
element.type = "created";
});
str = JSON.stringify(data);
console.log(str);
const myObj = {
"id": "222",
"list": [
{
"name": "Tony",
}
],
};
myObj.list[0].type = "created";
This is the way you can do this. But you'd better use secified index of list items;
const index = 0; // Or any other way to get this
myObj.list[index].type = "created";

How can I extract a json from a string in javascript

I need to extract json from a particular string which looks like this:
'loglocale=
{
"seed": "pqr",
"pageHashCode": "xxx",
"timestamp": 1553589859880,
"channel": "mobile",
"serviceVersion": "1.0",
"language": "en-CHN"
}
; regStatus=xx; s_dslv=34; s_fid=65-64748; s_vn=64678%26vn%3D1',
groups: undefined ]
I have tried this but could not extract it .
var regex=cookies.match(/{"seed":(\w|\W)*"channel":(\w|\W)*}/);
What is the solution I could use?
Thanks in advance:)
If you know there is only a single plain JSON object like this in the string, you can use this regex to capture the curly braces and everything in between:
const curlyBracesInclusive = /\{([^}]+)\}/
const arr = string.match(curlyBracesInclusive)
// arr[0] will be a the JSON string, if one was found
This is no way guarantees the string is valid JSON. So if you want to run JSON.parse on the result, be aware it will throw an error if the string is invalid.
For the loglocale:
let dataJSON = `
'loglocale=
{
"seed": "pqr",
"pageHashCode": "xxx",
"timestamp": 1553589859880,
"channel": "mobile",
"serviceVersion": "1.0",
"language": "en-CHN"
}
; regStatus=xx; s_dslv=34; s_fid=65-64748; s_vn=64678%26vn%3D1',
groups: undefined ]`
then:
let string = dataJSON.substring(
dataJSON.indexOf("loglocale=") + 10,
dataJSON.lastIndexOf("; regStatus")
)
JSON.parse(string);

Adding a variable name to a JSON list?

I'm writing this in Python and I want to be able to modify this JSON file
from this,
{
"name": "UVIDOCK",
"date": "03/14/2018",
"cola": "18:18:00",
"colb": "6.70000"
}
to this
window.data = {
"name": "UVIDOCK",
"date": "03/14/2018",
"cola": "18:18:00",
"colb": "6.70000"
}
Appreciate the help in advance.
So do you want a string with your JSON and a variable name? Assuming yes, but keeping in mind that it will not be a valid JSON, the solution will be:
import json
data = { "name": "UVIDOCK", "date": "03/14/2018", "cola": "18:18:00", "colb": "6.70000" }
jsonString = "window.data = " + json.dumps(data)
print (jsonString)
## Output: window.data = {"name": "UVIDOCK", "date": "03/14/2018", "cola": "18:18:00", "colb": "6.70000"}

Can valid JSON file consist of only one single object's description?

Example of given JSON file is as follows:
result = {
"name": "Foo",
"id": "10001",
"values": "1,2,3,4"
};
No, that is not valid JSON.
First, JSON is a string. What you have in the question is a JavaScript object literal expression assigned to the variable result.
Go to https://jsonlint.com/ , paste your file into the box, and click Validate. You will see the following output:
Error: Parse error on line 1:
result = { "name":
^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
As you can see from the JSON specification , you can't have a variable as a top-level entity. The valid entities in a JSON string are:
a string
an object
an array
a number
Your result variable is not one of those things. It's a variable, which is only valid in JavaScript.
objLiteral = {
"name": "Foo",
"id": "10001",
"values": "1,2,3,4"
};
jsonString = '{ "name": "Foo", "id": "10001", "values": "1,2,3,4" }';
var myObj = JSON.parse( jsonString );
console.log(objLiteral);
console.log(myObj);
console.log(objLiteral.name);
console.log(myObj.name);
<pre>Sample javascript</pre>

AJAX / javascript: parsing JSON that contains an array

I'm trying to parse a JSON message that my page gets through an AJAX response however, it keeps throwing the following error and I have no clue why:
"SyntaxError: JSON.parse: expected ',' or ']' after array element of the JSON data"
Here is what my page's javascript looks like:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var Response = JSON.parse(xhttp.responseText);
}
}
And here is what the JSON the server returns looks like:
{
"Error": "",
"ClientInfo": [{
"ID": 1,
"Name": "Bill"
}, {
"ID": 2,
"Name": "Sally"
}]
}
Any idea what I'm doing wrong? JSON validators say it's valid JSON....
UPDATE
It's that Error: key that's making the parser vomit it back out. See the demo.
Updated demo to include the JSON with Error: to compare results. Unfortunately, I had to comment out the console logged the error JSON because the debugger picked up on the Script error immediately. Fortunately, the demo still functions so you can ignore the initial error after loading.
TEST 1
Try the info button first. [Result: Sally]
Next click the error0 button. [Result: Sally]
Then try the error1 button. [Result: undefined]
So it seems to parse if you:
Remove the Error:""
OR
Place the Error: "" inside the array.
TEST 2
Copy the info JSON then validate it. JSONLint
When you use JSONLint, you must strip it:
{
"ClientInfo": [
{
"ID": 1,
"Name": "Bill"
},
{
"ID": 2,
"Name": "Sally"
}
]
}
Now copy the error JSON and validate it.
{
"Error": "",
"ClientInfo": [{
"ID": 1,
"Name": "Bill"
}, {
"ID": 2,
"Name": "Sally"
}]
}
Both of them should be valid, yet the debugger and the parser reject the error JSON.
Snippet
// Prepare JSON
var info =
'{"ClientInfo": [' +
'{"ID": 1, "Name": "Bill"},' +
'{"ID": 2, "Name": "Sally"} ]}';
var error0 =
'{"ClientInfo": [' +
'{"ID": 1, "Name": "Bill"},' +
'{"ID": 2, "Name": "Sally"},' +
'{"Error": ""} ]}';
var error1 =
'{"Error": ""},' +
'{"ClientInfo": [' +
'{"ID": 1, "Name": "Bill"},' +
'{"ID": 2, "Name": "Sally"} ]}';
// Create a function that parses JSON Object
function JSONObj(json) {
var jsonObj = JSON.parse(json);
return jsonObj;
}
// A function that logs results one at a time so we can compare results
function processLog(result) {
console.log('Result: ' + result);
}
/* Test info and errors */
var lastClient = JSONObj(info).ClientInfo[1].Name;
var errorA = JSONObj(error0).ClientInfo[1].Name;
var errorB = JSONObj(error1).ClientInfo[1].Name;
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<ol>
<li>Remove this: <pre><code>"Error": "",</code></pre>
</li>
<li>Separate into segments (see script)</li>
<li>Wrap each segment with single quotes `'`</li>
<li>Add a `+` after each segment</li>
</ol>
<button onclick="processLog(lastClient);">info</button>
<button onclick="processLog(errorA);">error0</button>
<button onclick="processLog(errorB);">error1</button>
Json parser takes in json string and parses it. You already have a json object

Categories