Javascript replace for equal symbol - javascript

I am getting my response as following
var val = {"Type"=>"D","Number"=>33"}
From above i try to change like this
var MyArray = {"Type": "D", "Number": "33"};
for(key in MyArray)
{
alert("key " + key
+ " has value "
+ MyArray[key]);
}
I tried replace, replace all but those not working. Any suggestions?
Server side code pasted from comments...
new_transfer_header = #params['my_extra_param']
p new_transfer_header,'------------ ew_transfer_header----------,new_transfer_header.class
WebView.execute_js("replaceDeliveryWithScanUnit('#{new_transfer_header}')")
puts result as "{\"Type\"=>\"D\", \"Number\"=>\"33\"}

var val = {"Type"=>"D","Number"=>33"}
Is invalid JavaScript - there is no way to fix it within the same script/script block since it fails parsing.
Likely you need to eliminate extra HTML encoding that somone done for this chunk of script on the server.
If it is text received by some AJAX call you should be able to replace " and similar values with corresponding characters and than parse with JSON.parse.

you could use string.replace and cal eval on the result I think, but would it be better to get valid json from the server ?

Related

Node-Red: Parse JavaScript Object with Double value

I am using node-RED to call in data from a robot. In the debug window it says it is a 'msg: Object', and when I copy it to a notepad it takes the format: {"topic":"","payload":27.659992218017578,"_session":{"type":"tcp","id":"0151ff7339437ec6"},"_msgid":"6a6897605a523366"}
I am also not sure if this is a JSON object or not, as I see examples with '' around the brackets.
I am trying to use the function node within node-red to parse this to attain the "payload" value. However, it keeps returning as undefined.
I am using the script:
var json =msg.payload;
var obj = JSON.parse(json);
msg.payload = console.log(obj.payload);
return msg;
I am a beginner to javascript and JSON, however I have tried searching and all examples only have integers as the parsing value. I am also unsure if the value name itself 'payload' is causing an issue. I have also attempted to stringify and using 'getDouble' but had no luck, which I owe to my lack of experience.
I appreciate any guidance.
You don't need to do anything. The value of msg.payload is already a double.
Without a lot more context of what you are trying to do there isn't anything else that we can say here.
After the node that gets the above information (the data in {} in the question}, I then used the function node to construct the message that I wanted to sent to the IIOT platform. I did
const str = msg.payload
msg.payload = " ," + str
// where the text I required was in " "
return msg
Also this works:
msg.payload = "," + msg.payload
return msg
And then I used the MQTT output node to publish this to the IIOT platform

Generating fully valid JSON with client-side JavaScript

So I am trying to create a JSON explorer / editor. I am able to parse the initial JSON into the div and format it how I like.
this is the function i use to loop through the initial JSON
_iterate(_tab, raw_json){
var tab = _tab;
tab++;
for(var key1 in raw_json){
var data_type = typeof raw_json[key1];
var d = String(raw_json[key1])
if(d == String){
d = "String";
}
if(d == Number){
d= "Number"
}
if(data_type == "object" || data_type == "array"){
this.input.append(`<json-tab tab-width="${tab}"></json-tab><div class="json-editor-input-container-2 -je-${data_type}">'<span class="-je-key">${key1}</span>' :{</div></br>`)
this._iterate(tab, raw_json[key1])
}else{
this.input.append(`<div class="json-editor-row"><json-tab tab-width="${tab}"></json-tab><div class="json-editor-input-container-2">'<span class="-je-key">${key1}<span>' : '<div class="json-editor-input -je-${data_type}" contenteditable="true" for="{key: '${key1}', data: '${d}'}"></div>', </div></br></div>`)
}
}
this.input.append(`<json-tab tab-width="${tab -1}"></json-tab>},</br>`)
}
in order to save the JSON I was going to retrieve the JSON from the text of the div using
getJSON(){
var json_text = this.input.text().slice(0, -1)
return JSON.parse(`"${json_text}"`)
}
right now this is able to be parse by JSON.parse(); but when i want to console.log(getJSON()[0]) this returns {
am i not formating the JSON correctly. a live example of this can be found here
First, your console.log result doesn't make sense. A parsed JSON object is now usable in JavaScript and, if has (only) properties x and y, would result in undefined when requesting property 0 as you have. It looks like your call to console.log was to a different (earlier?) version of the getJSON() function, where it returned the raw string, and in that case it makes sense that you're just retrieving the first character of the JSON text: "{".
But then, assuming the version of getJSON() as written, it would actually throw a parse exception:
VM1511:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 1
Looking at your site, I was able to do, in the console:
jsonString = $('json-editor').text()
// value: "{'partName' : '', 'partRevision' : '', ..."
That is illegal JSON. JSON specifies (only) the quotation mark " for strings (Unicode/ASCII 0x22) on page 7 of its specification.
The fact that 'partName' is legal as a JavaScript string literal is irrelevant but perhaps confusing.
As a minor style point, simplify JSON.parse(`"${json_text}"`) to JSON.parse(json_text).
#BaseZen's answer was very helpful for me to understand what was going wrong with my code. My JSON was incorrectly formatted even though online linters say its correct. Along with what BaseZen pointed out, JSON.parse() will not work with trailing commas. To fix this:
_remove_trailing_commas(json_string){
var regex = /\,(?!\s*?[\{\[\"\'\w])/g;
return json_string.replace(regex, '');
}
I found this information at SO post JSON Remove trailiing comma from last object
SO user Dima Parzhitsky's answer was what helped me also figure out this question.

How to replace 'special' characters in a string of code with an expanded piece of that same code?

I'm creating a chrome extension that basically finds a string of text such as this (note the different numbers):
id%22%3A99986%2C%22name%22%3A%22null%22%7D%2C%7B%22id%22%3A1002938%2C%22name%22%3A%22null%22%7D%2C%7B%22
and then usese javascript to swap that text above with this:
id%22%3A77764%2C%22name%22%3A%22null%22%7D%2C%7B%22id%22%3A77984%2C%22name%22%3A%22null%22%7D%2C%7B%22id%22%3A87746%2C%22name%22%3A%22null%22%7D%2C%7B%22
I can't manage to make this work whatsoever. All I'm able to do is swap out the ID numbers and replace individual parts of the code whereas I want to improve it by replacing with larger pieces of code. Can someone help me get past this because I'm confused.
Here is the code that works for me:
document.body.innerHTML = document.body.innerHTML.replace(/99986/g, '77764');
What I'm trying to do is to replace one piece of code with two pieces of code (obviously wrong but it's clear what I'm trying to do):
document.body.innerHTML = document.body.innerHTML.replace(/id%22%3A99986%2C%22name%22%3A%22null%22%7D%2C%7B%22/g, 'id%22%3A77764%2C%22name%22%3A%22null%22%7D%2C%7B%22id%22%3A77984%2C%22name%22%3A%22null%22%7D%2C%7B%22');
Update 1:
Thank you Emeeus, your code worked great! Unfortunately I made an error in my example so I had to fix it up a bit from my end. This is the new code using your layout:
var strA =
"%7Bid%22%3A1001%2C%22name%22%3A%22The+Antique+Store%22%7D%2C%7B%22id%22%3A1010%2C%22name%22%3A%22Clothes%22%7D%2C%7B%22id%22%3A1349%2C%22name%22%3A%22Old+Store%22%7D";
var strB = "%7Bid%22%3A1001%2C%22name%22%3A%22The+Modern+Store%22%7D%2C%7B%22id%22%3A1010%2C%22name%22%3A%22Clothes%22%7D%2C%7B%22id%22%3A1349%2C%22name%22%3A%22New+Store%22%7D";
var arrA = JSON.parse(decodeURIComponent(',{""' + strA + '",:""}'));
var arrB = JSON.parse(decodeURIComponent(',{""' + strB + '",:""}'));
console.log(arrA)
console.log(arrB)
var res = Object.assign(arrA, arrB);
console.log(encodeURIComponent(JSON.stringify(res)))
But I'm met with this error "Error: Unexpected token , in JSON at position 0". Any ideas?
I think you should check if the typeof string you are trying to replace is string. I tested, check if that solves your problem.
See screenshot:
Your strings are parts of a JSON URI-encoded, so I suggest first to decode the strings an then parse them using JSON.parse, then you could work with objects literals, which is easier most of times, here an example:
var strA = "id%22%3A99986%2C%22name%22%3A%22null%22%7D%2C%7B%22id%22%3A1002938%2C%22name%22%3A%22null%22%7D%2C%7B%22";
var strB = "id%22%3A77764%2C%22name%22%3A%22null%22%7D%2C%7B%22id%22%3A77984%2C%22name%22%3A%22null%22%7D%2C%7B%22id%22%3A87746%2C%22name%22%3A%22null%22%7D%2C%7B%22";
var arrA = JSON.parse(decodeURIComponent('[{"' + strA + '":""}]'));
var arrB = JSON.parse(decodeURIComponent('[{"' + strB + '":""}]'));
console.log(arrA)
console.log(arrB)
var res = Object.assign(arrA, arrB);//<-- example
console.log(encodeURIComponent(JSON.stringify(res)))//<-- you could encode the result again

How to parse JSON that has inner layers using Javascript?

I can eval simple JSON with javascript.
var json = '{"amount":"50","id":"3"}';
var out = eval("{" + json + "}");
Now I am using JPA with REST and JSON-nized query result would include table name which makes
JSON having inner JSON so simple eval wouldn't work.
{"inventory":{"amount":"50","id":"3"}}
I've looked around the web for solution but can't find my case.
Should I just do string manipulation and extract {"amount":"50","id":"3"} part?
Or is there other way?
Yes, there is another (better) way! Use JSON.parse() to parse your JSON and get your object out:
var obj = JSON.parse(jsonString);
//then, for example...
var amount = obj.inventory.amount;
For older browsers (IE <8 for example) without native JSON support, include json2.js so this above still works.
Even this should work:
var json = '{"inventory":{"amount":"50","id":"3"}}';
var out = eval("{" + json + "}");
alert(out.inventory.amount);
But better to use JSON.parse
Aniway, I think that the proper way to perform a simple eval is to have the json string surrounded with parenthesis, not curly brackets...
var out = eval("(" + json + ")");
Cf. https://github.com/douglascrockford/JSON-js/blob/master/json.js :
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');

JSON Parser error

I am using the json parser from json.org to handle data from my application. The problem is that the parser cannot handle some json formats.
One request receives the data below.
<?php
$obj = array("cities"=>array("city1","city2","city3","city4","city5"));
echo json_encode($obj);
?>
Results in the json below
{
"cities": ["city1","city2","city3","city4","city5"]
}
the code below handles the above data
var data = json_parse(XMLHttpRequestObject.responseText, function (key, value){
alert(key +' = '+value);
});
The parser fails and throws an error.
Does anyone know how to handle such an object.
I executed the following for a quick test and it seems to work:
var text = '{ "cities": ["city1","city2","city3","city4","city5"] }';
var data = json_parse(text, function (key, value){
document.write(key + ' = ' + value + '<br/>');
});
document.write('result = ' + data);
It recursively walks the structure and the result is this:
0 = city1
1 = city2
2 = city3
3 = city4
4 = city5
cities = ,,,,
= [object Object]
result = undefined
What is in your XMLHttpRequestObject.responseText field?
Also, aren't you supposed to return a value from your function(key, value)?
You need to put your keys and values into double quotes:
{
"cities": ["city1","city2","city3","city4","city5"]
}
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
You can use jsonlint to validate the code.
I'd wager that the problem lies in your data. The '' before city3 is wrong.
It would help if you include some information on the error thrown.
The parser fails because the JSON data is malformed. There are two quotes in front of city3 and the starting quote for city4 is missing.
{
cities: ['city1','city2','city3','city4','city5']
}
Are you in control of the code that generates this output? It looks like it's being built by hand, while if possible it should be generated using a JSON library.
PHP example:
$output = array(
'cities' => array('city1', 'city2', 'city3', 'city4', 'city5')
);
echo json_encode($output);
Output:
{"cities":["city1","city2","city3","city4","city5"]}
The problem seems to be in your application's json encoding algorithm.
Since you did't specify the application language, I cannot tell you the exact function/method to use, but I suggest you to use standard json encoding techniques instead reinventing the wheel.
For example in php you can use the json_encode standard function of one of the many encoding libraries in the open source world.

Categories

Resources