How to: React serialise multidimensional array and unserialise it in PHP - javascript

-- Edit 2--
I'm placing this on top since I'm narrowing down on the problem.
I send this string nested within a bigger array the combines all the attributes for a WP shortcode. The problem lays within the square brackets.
{“key”:”post_type”,”value”:[“news”,”agenda"]}
My best ques is that I need to escape the square brackets or to search replace on both sides and use a placeholder like (squareBracketOpen).
Or is there another way to serialize/unserialize an array?
The problem lays within the square brackets.
-- / Edit 2 --
I’m working in React and PHP and I’m tying to add something on top of a Wordpress Plugin. This uses React, which I’m not familiar with at all :)
Right now I have zero knowledge of react, but I’m getting stuff to work bit by bit. There is one thing though I don’t know how to solve. I’ll start with the quesion:
How do I serialise a multidimensional array in React and unserialise it in PHP?
If, in any case I miss translate my question, let me state my goal as following:
I have an multidimensional array in React and I want to pass it to PHP and reuse it as an multidimensional array.
This would be the array:
Array {
[key] => “post_type”,
[value] => Array {
[0] => “news”,
[1] => “agenda”
}
}
As a test in React I do
console.log(JSON.stringify(post_type));
// expected return {“key”:”post_type”,”value”:[“news”,”agenda"]}
--edit-- I've noticed it adds [ ] brackets as multidimensional. That's not right, right? -- end edit--
Looks fine to my knowledge, right?
Now in PHP I try to unserialise it with:
var_dump( unserialize ($postType ) );
// result: bool(false)
So I’m obvious doing something wrong. :)
Would anyone know how to properly serialise the multidimensional array in React and unserialise it in PHP to an array?

You'll need to do a json_decode($post_type, true) for it to be converted into a multi dimensional array.
Note, the second parameter true is what converts it to associative array.
So essentially, you'll be doing JSON.stringify then json_decode() for it work in php

Alright, finally. What I ended up doing is on the js/react side.
Serialize array to string. with JSON.stringify()
uri encoded the string. with encodeURIComponent()
And on the php side reversed it.
JS/React
let post_type_encoded = encodeURIComponent( JSON.stringify( post_type ) )
PHP
$postType = json_decode ( urldecode( $postTypeEncoded ) );

Related

Scrapy: Converting Javascript array to Json on Python

I have been struggling with a site I am scrapping using scrappy.
This site, returns a series of Javascript variables (array) with the products data.
Example:
datos[0] = ["12345","3M YELLOW CAT5E CABLE","6.81","1","A","N","N","N","N","N",0,0,0,0,0,"0","0","0","0","0","P","001-0030","12","40K8957","28396","250","Due: 30-12-1899",0.0000,1,"",\'\'];
datos[1] = ["12346","3M GREEN CAT5E CABLE","7.81","1","A","N","N","N","N","N",0,0,0,0,0,"0","0","0","0","0","P","001-0030","12","40K8957","28396","250","Due: 30-12-1899",0.0000,1,"",\'\'];
...
So on...
Fetching the array into a string with scrapy was easy, since the site response prints the variables.
The problem is I want to transform it into Json so I can process it and store it in a database table.
Normally I would use Javascript's function Json.stringify to convert it to Json and post it in PHP.
However when using Python's json.loads and even StringIO I am unable to load the array into json.
Probably is a format error, but I am unable to identify it, since I am not expert in Json nor Python.
EDIT:
I just realize since scrapy is unable to execute Javascript probably the main issue is that the data is just a string. I should format it into a Json format.
Any help is more than welcome.
Thank you.
If you wanted to take an array and create a json object, you could do something like this.
values = ["12345","3M YELLOW CAT5E CABLE","6.81","1","A","N","N","N","N","N",0,0,0,0,0,"0","0","0","0","0","P","001-0030","12","40K8957","28396","250","Due: 30-12-1899",0.0000,1]
keys = [x for x in range(len(values))]
d = dict(zip(keys, values))
x = json.dumps(d)
There is a section in the scrapy doc to find various ways to parse the JavaScript code. For your case, if you just need to have it in an array, you can use the regex to get the data.
Since the website you are scraping is not present in the question, I am assuming this would be a more straightforward way to get it, but you could use whichever way seems suitable.

How to parse the following json string into an object?

var jsonString = '{"DeviceId":3,"results":{"1":"[{\"x\":513,\"y\":565,\"width\":175,\"hight\":208}]"}}';
var message = JSON.parse(jsonString);
I got an error saying Unexpected token u in JSON at position 0
at JSON.parse.
Could you please guide me what's wrong?
THanks in advance!
At the last few characters looks wrong. The :212 has no sense as the value (that long array) for key "1" was already set, so that later :212 looks weird
Also enclosing it in single quotes it makes that all be like a huge string, and not as an array structure.
See Results key as value contains a sub array which contain "1" key which as value contains a string enclosing another json array (but escaped as plain string, so no structurally accesible for the main object . But that string if post -processed the :212 is paired to what? , no key, no comma neighter , to the precedent whole array which already was the value, not the key?. Anyway weird.
In your JSON string, there is wrong something with ":212", as it's not valid JSON, because it doesn't have any property that it's mapping the value for. For example, you are mapping values for width and height with properties keys. But for "212", there is no property.
Here is the above JSON formatted:
var jsonString = '{"DeviceId":"3","results":{"1":"[{\\"x\\":513,\\"y\\":565,\\"width\\":175,\\"hight\\":208}]"}}'
var message = JSON.parse(jsonString);
If you want to format the results, you can do to it, there is no error on it:
JSON.parse(message.results['1'])
Here is the JS Bin link for above code: https://jsbin.com/fiyeyet/edit?js,console
Just an advice
Professional code is all about proper spacing, proper identation , proper commenting, don't try to write down all within one single line, structure it VISUALLY nice to see nice to read nice to comprehend, and you will be approved in most jobs.
Hint: declare a normal array/object , convert it to json string using the proper function, then use the string variable returned by the function to test your code or whatever doing. That way, you can write down in the source really nice the structure.

recursively parse json in javascript to retrieve certain keys' values

I am new to javascript and every time i try learning it, I just end up in an immense amount of frustration and disgust ! No offense, but this is my opinion or perhaps I am too stupid to not understand how it works at all.
I have a simple requirement. I have a pretty deeply nested dictionary (which is what it is called in many backend languages) at hand. To be more specific it is the raw text of a postman collection. The collection itself could have multiple nested directories.
Now all I want to do is to be able to parse this dictionary and do something with it recursively.
For example, if I had to do the same in python I would do it as simply as :
def createRequests(self, dic):
total_reqs = 0
headers = {}
print type(dic)
keys = dic.keys()
if 'item' in keys:
print "Folder Found. Checking for Indivisual request inside current folder . . \n"
self.item_list = dic.get('item')
for each_item in self.item_list:
self.folder.append(self.createRequests(each_item))
else:
print "Found Indivisual request. Appending. . . \n"
temp_list = []
temp_list.append(dic)
self.requestList.append(temp_list)
return self.requestList
where dic would be my dictionary that I want to parse.
Is there any simple and straight forward way to do the same in Javascript?
Let's just say all I want to do is that if I have a text file that has properly formed json data in it and whose contents have been read into dataReadFromFile and then it has been converted into a JSON as :
var obj = JSON.parse(dataReadFromFile);
is there any simple and easy way to convert this JSON to dictionary or the dataReadFromFile directly into a dictionary such that I can say something like dictioanry.keys() if I wanted a list of the keys in it.
Note that the content of the file is not fixed. It may have multiple levels of nesting, which may not be known beforehand.

javascript array into object with same key names

I have an unusual problem to solve here. I have an array of Guids
[
"c01f8237-72c8-4fa6-9c53-1915750385aa",
"2c8a471b-c408-436c-81b1-3f3867d8ffb4",
"27a44d46-12bd-4784-ceed-57ada31b0e33"
]
This array has to be transformed into:
{
id: "c01f8237-72c8-4fa6-9c53-1915750385aa",
id: "2c8a471b-c408-436c-81b1-3f3867d8ffb4",
id: "27a44d46-12bd-4784-ceed-57ada31b0e33"
}
I know that shouldn't be done, but unfortunately cannot control the back end part. Any idea?
Thanks
The whole point of a dictionary key is that it uniquely maps to some value. Your desired output attempts to duplicate a key and therefore is neither possible nor does it make sense.
If you're passing this to a backend (as you suggest), then of course you can manually build a string to pass over the wire that duplicates keys in the payload, but you won't be able to actually do it in JavaScript first. You'll have to manually build the string.
Also note that you can call this format whatever you want, but you can't call it JSON and you can't use JSON libraries to build it (because it's not JSON). If your API expects a custom format, then you need to write code to build that custom format.
If all you want is a string just do something like
var str = '{' + idArray.map(function(id) {
return "id: "+id
}).join(',\n')+'}';
I have no idea what mime type you would put on that though since its not valid JSON.

regular expression to filter out part of key value in a json string

I have the following JSON string as part of a log line.
cells : {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"}
I want to filter out to the following format: {"Lac":"7824","Cid":"11983"}.
How can do this using regular expression ? in Javascript or Python ?
the keys are constant strings(Lac, CntryISO, ...), but the value strings are varying.
Why don't you just delete them in JavaScript?
var myJson = {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"};
delete myJson.Lac;
delete myJson.cId;
To expand and explain #alex answer:
JSON is a nested multi dimensional structure. Simply filtering the "string-ifiyed form of a Javascript object" (aka JSON) will work in very simple cases, but will rapidly fail when the structure is no longer flat or it starts to get complex with escaped fields, etc.
At that point you will need proper parsing logic. This is nicely supplied by Javascript itself, to quote #alexes code:
var myJson = {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"};
delete myJson.Lac;
delete myJson.cId;
Or, if you want to use python, the json module will work just fine:
http://docs.python.org/library/json.html
Good luck! :)
Why would you want to use regex for this when you can just use a JSON parser/serializer? Try cjson in Python if you are concerned about speed, it is faster than 'json' module in the Python standard library.

Categories

Resources