a
    Of                     @  s  d dl mZ d dlmZmZ d dlmZ d dlmZ d dlm	Z	 d dl
mZmZmZmZmZmZmZmZ d dlZd dlZd dlmZ d d	lmZmZ d d
lmZ d dlmZ d dlm Z  d dl!m"Z" d dl#m$Z$ d dl%m&Z& d dl'm(Z(m)Z) d dl*m+Z+ d dl,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 d dl5m6Z6 d dl7m8Z8 d dl9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZB d dlCmDZD d dlEmFZFmGZG d dlHmIZI erd dlJmKZKmLZL d dlMmNZN d dlOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZ d dl[m\Z\ eded dZ]edkd!d"d#d$d%d&d$d'd&d(d)d%d*d+d,d-d.d/Z^edld,d"d#d$d%d&d$d'd&d(d)d%d*d+d$d-d0d/Z^dmd8d"d#d$d%d&d$d'd&d(d)d%d9d+d#d-d:d/Z^G d;d< d<eZ_G d=d> d>e_Z`G d?d@ d@e_ZaG dAdB dBeaZbed d d d d d d d d d d d d d d d dCdDd#dEdFd)dGd&d&d#d#d#d&d%d(dHd*dIdJdKdLdMdNZced d d d d d d d d d d d d d d dOdDd#dPdFd)dGd&d&d#d#d#d&d%d(dHd*dIdJdQdLdRdNZced d d d d d d d d d d d d d d d dSdDd#dPdFd)dGd&d&d#d#d#d&d,d(dHd*dIdJdTdLdUdNZced d d d d d d d d d d d d d d d d dVdDd#dEdFd)dGd&d&d#d#d#d&d,d(dHd*dIdJdWdLdXdNZce"e8dY e8dZ d[ d\dd]ddd3d3d5ddd^d5dd6ddejdd_dVdDd#d`dFd)dGd&d&d#d#d#d&dHd(dHd9dIdJdadLdbdNZcG dcdd ddejeee] ZfG dedf dfZgG dgdh dhegZhG didj djegZidS )n    )annotations)ABCabstractmethod)abc)StringIO)islice)TYPE_CHECKINGAnyCallableGenericLiteralTypeVarfinaloverloadN)lib)ujson_dumpsujson_loads)iNaT)import_optional_dependencyAbstractMethodError)doc)find_stack_level)check_dtype_backend)
ensure_stris_string_dtype)PeriodDtype)
ArrowDtype	DataFrameIndex
MultiIndexSeriesisnanotnato_datetime)concat)_shared_docs)		IOHandlesdedup_namesextension_to_compressionfile_exists
get_handleis_fsspec_urlis_potential_multi_indexis_urlstringify_path)convert_to_line_delimits)build_table_schemaparse_table_schema)validate_integer)HashableMapping)TracebackType)CompressionOptionsDtypeArgDtypeBackendFilePath
IndexLabel
JSONEngineJSONSerializable
ReadBufferSelfStorageOptionsWriteBuffer)NDFrameFrameSeriesStrT)frameseries)bound.z0FilePath | WriteBuffer[str] | WriteBuffer[bytes]rB   
str | Nonestrintbool(Callable[[Any], JSONSerializable] | Noner7   bool | Noner@   zLiteral['a', 'w']None)path_or_bufobjorientdate_formatdouble_precisionforce_ascii	date_unitdefault_handlerlinescompressionindexindentstorage_optionsmodereturnc                 C  s   d S N rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r^   r^   M/var/www/ai-form-bot/venv/lib/python3.9/site-packages/pandas/io/json/_json.pyto_jsond   s    ra   c                 C  s   d S r]   r^   r_   r^   r^   r`   ra   x   s    epoch
   TmsFinferwz7FilePath | WriteBuffer[str] | WriteBuffer[bytes] | NoneStorageOptions | Nonec                 C  sr  |dv r|
du rt dn&|dv r4|
du r4t dn|
d u r@d}
|rT|dkrTt d|d	vrpd
| d}t ||dkr|r|dkrd}t ||dkrt|tr|j|jpdd}|dkrt|trt}n(t|trt}nt|trt}nt	d|||||||||
|d	
 }|r t|}| d urjt| ||	|d}|j
| W d    n1 s^0    Y  n|S d S )N)recordsvaluesTzT'index=True' is only valid when 'orient' is 'split', 'table', 'index', or 'columns'.rX   columnsFzV'index=False' is only valid when 'orient' is 'split', 'table', 'records', or 'values'.rh   z3'lines' keyword only valid when 'orient' is records)arf   zmode=z@ is not a valid option.Only 'w' and 'a' are currently supported.rl   zNmode='a' (append) is only supported when lines is True and orient is 'records'tableri   )namez''obj' should be a Series or a DataFrame)rP   rQ   rR   ensure_asciirT   rU   rX   rY   )rW   rZ   )
ValueError
isinstancer!   Zto_framern   r   JSONTableWriterSeriesWriterFrameWriterNotImplementedErrorwriter0   r+   handle)rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   msgwritershandlesr^   r^   r`   ra      sd    




.c                   @  sj   e Zd ZU ded< ddddddddd	dd
d
ddZd
dddZddddZeeddddZ	dS )WriterrH   _default_orientNr   rB   rG   rI   rJ   rK   rM   )
rO   rP   rQ   rR   ro   rT   rX   rU   rY   r\   c
           
      C  sV   || _ |d u r| j}|| _|| _|| _|| _|| _|| _|| _|	| _	d | _
|   d S r]   )rO   r}   rP   rQ   rR   ro   rT   rU   rX   rY   Zis_copy_format_axes)
selfrO   rP   rQ   rR   ro   rT   rX   rU   rY   r^   r^   r`   __init__   s    zWriter.__init__r\   c                 C  s   t | d S r]   r   r   r^   r^   r`   r~     s    zWriter._format_axesc              
   C  s0   | j dk}t| j| j| j| j| j|| j| jdS )Niso)rP   rR   ro   rT   	iso_datesrU   rY   )	rQ   r   obj_to_writerP   rR   ro   rT   rU   rY   )r   r   r^   r^   r`   rv     s    
zWriter.write"NDFrame | Mapping[IndexLabel, Any]c                 C  s   dS )zObject to write in JSON format.Nr^   r   r^   r^   r`   r     s    zWriter.obj_to_write)Nr   )
__name__
__module____qualname____annotations__r   r~   rv   propertyr   r   r^   r^   r^   r`   r|      s   
  "r|   c                   @  s0   e Zd ZdZeddddZddddZd	S )
rs   rX   r   r   c                 C  s,   | j s"| jdkr"| jj| jjdS | jS d S )Nsplit)rn   data)rX   rP   rO   rn   ri   r   r^   r^   r`   r     s    zSeriesWriter.obj_to_writerM   c                 C  s*   | j jjs&| jdkr&td| j dd S )NrX   z(Series index must be unique for orient='')rO   rX   	is_uniquerP   rp   r   r^   r^   r`   r~   "  s    zSeriesWriter._format_axesNr   r   r   r}   r   r   r~   r^   r^   r^   r`   rs     s   rs   c                   @  s0   e Zd ZdZeddddZddddZd	S )
rt   rk   r   r   c                 C  s0   | j s&| jdkr&| jjdd}|d= n| j}|S )Nr   )rP   rX   )rX   rP   rO   to_dict)r   r   r^   r^   r`   r   *  s
    zFrameWriter.obj_to_writerM   c                 C  sP   | j jjs&| jdv r&td| j d| j jjsL| jdv rLtd| j ddS )z:
        Try to format axes if they are datelike.
        rj   z+DataFrame index must be unique for orient='z'.)rX   rk   rh   z-DataFrame columns must be unique for orient='N)rO   rX   r   rP   rp   rk   r   r^   r^   r`   r~   3  s    zFrameWriter._format_axesNr   r^   r^   r^   r`   rt   '  s   rt   c                      sJ   e Zd ZdZdddddddddd	d
	 fddZeddddZ  ZS )rr   rh   Nr   rG   rH   rI   rJ   rK   rM   )	rP   rQ   rR   ro   rT   rX   rU   rY   r\   c
                   s0  t  j|||||||||	d	 |dkr:d| d}
t|
t|| jd| _|jdkrht|jt	rht
d|jdkr|jt|jjv st|j|jjrd	}
t|
| }|jd
gdj}t|r|| dd ||< t|jjtr|j |_| js|jdd| _n|jdd| _d| _d| _|| _dS )z
        Adds a `schema` attribute with the Table Schema, resets
        the index (can't do in caller, because the schema inference needs
        to know what the index is, forces orient to records, and forces
        date_format to 'iso'.
        )rU   rY   r   z8Trying to write with `orient='table'` and `date_format='zH'`. Table Schema requires dates to be formatted with `date_format='iso'`rX      z6orient='table' is not supported for MultiIndex columns   z/Overlapping names between the index and columns	timedelta)includec                 S  s   |   S r]   )	isoformat)xr^   r^   r`   <lambda>      z*JSONTableWriter.__init__.<locals>.<lambda>T)ZdropFrh   N)superr   rp   r1   rX   schemandimrq   rk   r    ru   rn   setnameslenintersectioncopyZselect_dtypesmapdtyper   Zto_timestampZreset_indexrO   rQ   rP   )r   rO   rP   rQ   rR   ro   rT   rX   rU   rY   rx   Z
timedeltas	__class__r^   r`   r   H  sT    zJSONTableWriter.__init__r   r   c                 C  s   | j | jdS )N)r   r   )r   rO   r   r^   r^   r`   r     s    zJSONTableWriter.obj_to_write)Nr   )r   r   r   r}   r   r   r   __classcell__r^   r^   r   r`   rr   E  s     $Hrr   )rP   typr   convert_axesconvert_dateskeep_default_datesprecise_floatrT   encodingencoding_errorsrV   rW   nrowsrZ   dtype_backendenginez.FilePath | ReadBuffer[str] | ReadBuffer[bytes]zLiteral['frame']DtypeArg | Nonebool | list[str]
int | NoneDtypeBackend | lib.NoDefaultr<   JsonReader[Literal['frame']])rN   rP   r   r   r   r   r   r   rT   r   r   rV   	chunksizerW   r   rZ   r   r   r\   c                C  s   d S r]   r^   rN   rP   r   r   r   r   r   r   rT   r   r   rV   r   rW   r   rZ   r   r   r^   r^   r`   	read_json  s    r   )rP   r   r   r   r   r   rT   r   r   rV   rW   r   rZ   r   r   zLiteral['series']JsonReader[Literal['series']]c                C  s   d S r]   r^   r   r^   r^   r`   r     s    )rP   r   r   r   r   r   rT   r   r   rV   r   rW   r   rZ   r   r   r!   c                C  s   d S r]   r^   r   r^   r^   r`   r     s    )rP   r   r   r   r   r   r   rT   r   r   rV   r   rW   r   rZ   r   r   r   c                C  s   d S r]   r^   r   r^   r^   r`   r     s    rZ   decompression_optionsrN   )rZ   r   rD   strictujsonzLiteral['frame', 'series']zDataFrame | Series | JsonReaderc                C  s   |dkr|rt d|dkr(|r(t dt| |du rD|dkrDd}|du rX|dkrXd}t| |||||||||	||||||
||d}|r|S | S dS )a|"  
    Convert a JSON string to pandas object.

    Parameters
    ----------
    path_or_buf : a valid JSON str, path object or file-like object
        Any valid string path is acceptable. The string could be a URL. Valid
        URL schemes include http, ftp, s3, and file. For file URLs, a host is
        expected. A local file could be:
        ``file://localhost/path/to/table.json``.

        If you want to pass in a path object, pandas accepts any
        ``os.PathLike``.

        By file-like object, we refer to objects with a ``read()`` method,
        such as a file handle (e.g. via builtin ``open`` function)
        or ``StringIO``.

        .. deprecated:: 2.1.0
            Passing json literal strings is deprecated.

    orient : str, optional
        Indication of expected JSON string format.
        Compatible JSON strings can be produced by ``to_json()`` with a
        corresponding orient value.
        The set of possible orients is:

        - ``'split'`` : dict like
          ``{{index -> [index], columns -> [columns], data -> [values]}}``
        - ``'records'`` : list like
          ``[{{column -> value}}, ... , {{column -> value}}]``
        - ``'index'`` : dict like ``{{index -> {{column -> value}}}}``
        - ``'columns'`` : dict like ``{{column -> {{index -> value}}}}``
        - ``'values'`` : just the values array
        - ``'table'`` : dict like ``{{'schema': {{schema}}, 'data': {{data}}}}``

        The allowed and default values depend on the value
        of the `typ` parameter.

        * when ``typ == 'series'``,

          - allowed orients are ``{{'split','records','index'}}``
          - default is ``'index'``
          - The Series index must be unique for orient ``'index'``.

        * when ``typ == 'frame'``,

          - allowed orients are ``{{'split','records','index',
            'columns','values', 'table'}}``
          - default is ``'columns'``
          - The DataFrame index must be unique for orients ``'index'`` and
            ``'columns'``.
          - The DataFrame columns must be unique for orients ``'index'``,
            ``'columns'``, and ``'records'``.

    typ : {{'frame', 'series'}}, default 'frame'
        The type of object to recover.

    dtype : bool or dict, default None
        If True, infer dtypes; if a dict of column to dtype, then use those;
        if False, then don't infer dtypes at all, applies only to the data.

        For all ``orient`` values except ``'table'``, default is True.

    convert_axes : bool, default None
        Try to convert the axes to the proper dtypes.

        For all ``orient`` values except ``'table'``, default is True.

    convert_dates : bool or list of str, default True
        If True then default datelike columns may be converted (depending on
        keep_default_dates).
        If False, no dates will be converted.
        If a list of column names, then those columns will be converted and
        default datelike columns may also be converted (depending on
        keep_default_dates).

    keep_default_dates : bool, default True
        If parsing dates (convert_dates is not False), then try to parse the
        default datelike columns.
        A column label is datelike if

        * it ends with ``'_at'``,

        * it ends with ``'_time'``,

        * it begins with ``'timestamp'``,

        * it is ``'modified'``, or

        * it is ``'date'``.

    precise_float : bool, default False
        Set to enable usage of higher precision (strtod) function when
        decoding string to double values. Default (False) is to use fast but
        less precise builtin functionality.

    date_unit : str, default None
        The timestamp unit to detect if converting dates. The default behaviour
        is to try and detect the correct precision, but if this is not desired
        then pass one of 's', 'ms', 'us' or 'ns' to force parsing only seconds,
        milliseconds, microseconds or nanoseconds respectively.

    encoding : str, default is 'utf-8'
        The encoding to use to decode py3 bytes.

    encoding_errors : str, optional, default "strict"
        How encoding errors are treated. `List of possible values
        <https://docs.python.org/3/library/codecs.html#error-handlers>`_ .

        .. versionadded:: 1.3.0

    lines : bool, default False
        Read the file as a json object per line.

    chunksize : int, optional
        Return JsonReader object for iteration.
        See the `line-delimited json docs
        <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#line-delimited-json>`_
        for more information on ``chunksize``.
        This can only be passed if `lines=True`.
        If this is None, the file will be read into memory all at once.
    {decompression_options}

        .. versionchanged:: 1.4.0 Zstandard support.

    nrows : int, optional
        The number of lines from the line-delimited jsonfile that has to be read.
        This can only be passed if `lines=True`.
        If this is None, all the rows will be returned.

    {storage_options}

    dtype_backend : {{'numpy_nullable', 'pyarrow'}}, default 'numpy_nullable'
        Back-end data type applied to the resultant :class:`DataFrame`
        (still experimental). Behaviour is as follows:

        * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame`
          (default).
        * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype`
          DataFrame.

        .. versionadded:: 2.0

    engine : {{"ujson", "pyarrow"}}, default "ujson"
        Parser engine to use. The ``"pyarrow"`` engine is only available when
        ``lines=True``.

        .. versionadded:: 2.0

    Returns
    -------
    Series, DataFrame, or pandas.api.typing.JsonReader
        A JsonReader is returned when ``chunksize`` is not ``0`` or ``None``.
        Otherwise, the type returned depends on the value of ``typ``.

    See Also
    --------
    DataFrame.to_json : Convert a DataFrame to a JSON string.
    Series.to_json : Convert a Series to a JSON string.
    json_normalize : Normalize semi-structured JSON data into a flat table.

    Notes
    -----
    Specific to ``orient='table'``, if a :class:`DataFrame` with a literal
    :class:`Index` name of `index` gets written with :func:`to_json`, the
    subsequent read operation will incorrectly set the :class:`Index` name to
    ``None``. This is because `index` is also used by :func:`DataFrame.to_json`
    to denote a missing :class:`Index` name, and the subsequent
    :func:`read_json` operation cannot distinguish between the two. The same
    limitation is encountered with a :class:`MultiIndex` and any names
    beginning with ``'level_'``.

    Examples
    --------
    >>> from io import StringIO
    >>> df = pd.DataFrame([['a', 'b'], ['c', 'd']],
    ...                   index=['row 1', 'row 2'],
    ...                   columns=['col 1', 'col 2'])

    Encoding/decoding a Dataframe using ``'split'`` formatted JSON:

    >>> df.to_json(orient='split')
        '{{"columns":["col 1","col 2"],"index":["row 1","row 2"],"data":[["a","b"],["c","d"]]}}'
    >>> pd.read_json(StringIO(_), orient='split')
          col 1 col 2
    row 1     a     b
    row 2     c     d

    Encoding/decoding a Dataframe using ``'index'`` formatted JSON:

    >>> df.to_json(orient='index')
    '{{"row 1":{{"col 1":"a","col 2":"b"}},"row 2":{{"col 1":"c","col 2":"d"}}}}'

    >>> pd.read_json(StringIO(_), orient='index')
          col 1 col 2
    row 1     a     b
    row 2     c     d

    Encoding/decoding a Dataframe using ``'records'`` formatted JSON.
    Note that index labels are not preserved with this encoding.

    >>> df.to_json(orient='records')
    '[{{"col 1":"a","col 2":"b"}},{{"col 1":"c","col 2":"d"}}]'
    >>> pd.read_json(StringIO(_), orient='records')
      col 1 col 2
    0     a     b
    1     c     d

    Encoding with Table Schema

    >>> df.to_json(orient='table')
        '{{"schema":{{"fields":[{{"name":"index","type":"string"}},{{"name":"col 1","type":"string"}},{{"name":"col 2","type":"string"}}],"primaryKey":["index"],"pandas_version":"1.4.0"}},"data":[{{"index":"row 1","col 1":"a","col 2":"b"}},{{"index":"row 2","col 1":"c","col 2":"d"}}]}}'

    The following example uses ``dtype_backend="numpy_nullable"``

    >>> data = '''{{"index": {{"0": 0, "1": 1}},
    ...        "a": {{"0": 1, "1": null}},
    ...        "b": {{"0": 2.5, "1": 4.5}},
    ...        "c": {{"0": true, "1": false}},
    ...        "d": {{"0": "a", "1": "b"}},
    ...        "e": {{"0": 1577.2, "1": 1577.1}}}}'''
    >>> pd.read_json(StringIO(data), dtype_backend="numpy_nullable")
       index     a    b      c  d       e
    0      0     1  2.5   True  a  1577.2
    1      1  <NA>  4.5  False  b  1577.1
    rm   z)cannot pass both dtype and orient='table'z0cannot pass both convert_axes and orient='table'NT)rP   r   r   r   r   r   r   rT   r   rV   r   rW   r   rZ   r   r   r   )rp   r   
JsonReaderread)rN   rP   r   r   r   r   r   r   rT   r   r   rV   r   rW   r   rZ   r   r   Zjson_readerr^   r^   r`   r     sD      c                   @  s@  e Zd ZdZddejdfddddddd	dd
dddddddZdd Zdd ZddddZ	e
dddddZe
dd dd!dZe
d"d#dd$dZd#dd%dZd#dd&d'Zddd(d)Zd*dd+d,Ze
dddd-d.Ze
dd dd/d.Ze
d"d#dd0d.Zd#dd1d.Zd*dd2d3Zd4d5d6dd7d8d9ZdS ):r   z
    JsonReader provides an interface for reading in a JSON file.

    If initialized with ``lines=True`` and ``chunksize``, can be iterated over
    ``chunksize`` lines at a time. Otherwise, calling ``read`` reads in the
    whole document.
    Nr   r   rC   rL   rJ   r   r7   rg   rG   r   r<   rM   )r   r   r   r   rV   r   rW   r   rZ   r   r   r   r\   c                 C  sj  || _ || _|| _|| _|| _|| _|| _|	| _|
| _|| _	|| _
|| _|| _|| _d| _|| _|| _d | _|| _| j	dvrtd| j	 d| jd urtd| jd| _| jstd| j	dkrtd	| jd urtd
| jd| _| jstdt|tr | js d|v r tjdtt d | j	dkrD| js<td|| _n"| j	dkrf| |}| || _d S )Nr   >   pyarrowr   zThe engine type z is currently not supported.r   r   z*chunksize can only be passed if lines=Truer   z<currently pyarrow engine doesn't support chunksize parameterr   z&nrows can only be passed if lines=True
Passing literal json to 'read_json' is deprecated and will be removed in a future version. To read from a literal string, wrap it in a 'StringIO' object.
stacklevelzEcurrently pyarrow engine only supports the line-delimited JSON formatr   )rP   r   r   r   r   r   r   rT   r   r   rW   rZ   rV   r   
nrows_seenr   r   r{   r   rp   r3   rq   rH   warningswarnFutureWarningr   r   _get_data_from_filepath_preprocess_data)r   filepath_or_bufferrP   r   r   r   r   r   r   rT   r   rV   r   rW   r   rZ   r   r   r   r   r^   r^   r`   r   ;  sn    




zJsonReader.__init__c                 C  sd   t |drB| jsB| jsB|  | }W d   n1 s80    Y  t |ds`| jsX| jr`t|}|S )a&  
        At this point, the data either has a `read` attribute (e.g. a file
        object or a StringIO) or is a string that is a JSON document.

        If self.chunksize, we prepare the data for the `__next__` method.
        Otherwise, we read it into memory for the `read` method.
        r   N)hasattrr   r   r   r   )r   r   r^   r^   r`   r     s    &zJsonReader._preprocess_datac                 C  s   t |}t|tr*t|s*t|s*t|rRt|d| j| j| j	| j
d| _| jj}nVt|tr| dtdd tD  rt|std| dntjdtt d	 |S )
a  
        The function read_json accepts three input types:
            1. filepath (string-like)
            2. file-like object (e.g. open file object, StringIO)
            3. JSON string

        This method turns (1) into (2) to simplify the rest of the processing.
        It returns input types (2) and (3) unchanged.

        It raises FileNotFoundError if the input is a string ending in
        one of .json, .json.gz, .json.bz2, etc. but no such file exists.
        r)r   rW   rZ   errors).jsonc                 s  s   | ]}d | V  qdS )r   Nr^   ).0cr^   r^   r`   	<genexpr>  r   z5JsonReader._get_data_from_filepath.<locals>.<genexpr>zFile z does not existr   r   )r/   rq   rH   r.   r,   r*   r+   r   rW   rZ   r   r{   rw   lowerendswithtupler)   FileNotFoundErrorr   r   r   r   )r   r   r^   r^   r`   r     sB    
z"JsonReader._get_data_from_filepathrH   r   c                 C  s&   dd dd dd |D D  dS )zG
        Combines a list of JSON objects into one JSON object.
        [,c                 S  s   g | ]}|r|qS r^   r^   r   liner^   r^   r`   
<listcomp>  r   z-JsonReader._combine_lines.<locals>.<listcomp>c                 s  s   | ]}|  V  qd S r]   )stripr   r^   r^   r`   r     r   z,JsonReader._combine_lines.<locals>.<genexpr>])join)r   rV   r^   r^   r`   _combine_lines  s    $zJsonReader._combine_linesr   r   )r   r\   c                 C  s   d S r]   r^   r   r^   r^   r`   r     s    zJsonReader.readr   r!   c                 C  s   d S r]   r^   r   r^   r^   r`   r     s    z&JsonReader[Literal['frame', 'series']]zDataFrame | Seriesc                 C  s   d S r]   r^   r   r^   r^   r`   r     s    c           
      C  sX  | < | j dkrttd}|| j}| jdkr6t}n$| jdkrVddlm} | j}nd}|j	|dW  d   S | j dkr4| j
r| jrt| }q| jrtt| j| j}| |}| |}qt| j}|d	}	| | |	}n| | j}| jtjur"|jd
| jdW  d   S |W  d   S W d   n1 sJ0    Y  dS )zA
        Read the whole JSON input into a pandas object.
        r   zpyarrow.jsonZnumpy_nullabler   )_arrow_dtype_mappingN)Ztypes_mapperr   r   FZinfer_objectsr   )r   r   r   r   r   r   Zpandas.io._utilr   getZ	to_pandasrV   r   r%   r   listr   r   _get_object_parserr   r   r   
no_defaultconvert_dtypes)
r   Zpyarrow_jsonZpa_tablemappingr   rO   rV   
lines_jsonr   Z
data_linesr^   r^   r`   r     s8    







c              	   C  s   | j }| j}| j| j| j| j| j| j| j| jd}d}|dkrRt	|fi |
 }|dksb|du rt|tst||d< t|fi |
 }|S )z>
        Parses a json document into a pandas object.
        )rP   r   r   r   r   r   rT   r   NrD   rE   r   )r   r   rP   r   r   r   r   rT   r   FrameParserparserq   rJ   SeriesParser)r   jsonr   r   kwargsrO   r^   r^   r`   r   	  s&    

zJsonReader._get_object_parserc                 C  s   | j dur| j   dS )z
        If we opened a stream earlier, in _get_data_from_filepath, we should
        close it.

        If an open stream or file was passed, we leave it open.
        N)r{   closer   r^   r^   r`   r   $  s    
zJsonReader.closer?   c                 C  s   | S r]   r^   r   r^   r^   r`   __iter__.  s    zJsonReader.__iter__c                 C  s   d S r]   r^   r   r^   r^   r`   __next__1  s    zJsonReader.__next__c                 C  s   d S r]   r^   r   r^   r^   r`   r   5  s    c                 C  s   d S r]   r^   r   r^   r^   r`   r   9  s    c              
   C  s   | j r| j| j kr|   ttt| j| j}|s@|   tzB| |}| 	|}t
| j| jt| |_|  jt|7  _W n0 ty } z|   |W Y d }~n
d }~0 0 | jtjur|jd| jdS |S d S )NFr   )r   r   r   StopIterationr   r   r   r   r   r   ranger   rX   	Exceptionr   r   r   r   )r   rV   r   rO   exr^   r^   r`   r   =  s(    

c                 C  s   | S r]   r^   r   r^   r^   r`   	__enter__Y  s    zJsonReader.__enter__ztype[BaseException] | NonezBaseException | NonezTracebackType | None)exc_type	exc_value	tracebackr\   c                 C  s   |    d S r]   )r   )r   r   r   r   r^   r^   r`   __exit__\  s    zJsonReader.__exit__)r   r   r   __doc__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r^   r^   r^   r`   r   2  s8   (P0*
r   c                
   @  s   e Zd ZU ded< ded< dZdddd	dZded
< ddddddejfdddddddddddZe	dddddZ
e	dd ZddddZe	dddd Zddd!d"Ze	d,d#d$dddd%d&d'd(Ze	d$d%d)d*d+ZdS )-Parserztuple[str, ...]_split_keysrH   r}   )rz   rd   usnsi3l    ,b/ l    `'rl     F[L'r   NTFr   rJ   r   r   rM   )r   r   r   r   r   r   r   r\   c
           
      C  s   || _ |d u r| j}|| _|| _|d urX| }|| jvrJtd| j | j| | _n| jd | _|| _	|| _
|| _|| _|| _d | _|	| _d S )Nzdate_unit must be one of rz   )r   r}   rP   r   r   _STAMP_UNITSrp   _MIN_STAMPS	min_stampr   r   r   rT   r   rO   r   )
r   r   rP   r   r   r   r   r   rT   r   r^   r^   r`   r   r  s$    
zParser.__init__dict)decodedr\   c                 C  s8   t | t | j}|r4d|}td| dS )zT
        Checks that dict has only the appropriate keys for orient='split'.
        z, z!JSON data had unexpected key(s): N)r   keys
differencer   r   rp   )r   r  Zbad_keysZbad_keys_joinedr^   r^   r`   check_keys_split  s    
zParser.check_keys_splitc                 C  s2   |    | jd u rd S | jr$|   |   | jS r]   )_parserO   r   _convert_axes_try_convert_typesr   r^   r^   r`   r     s    
zParser.parser   c                 C  s   t | d S r]   r   r   r^   r^   r`   r    s    zParser._parsec                 C  sv   | j }|dusJ |jD ]X}||}t||jdd}| j||dddd\}}|rt||jdd}t| j || qdS )z&
        Try to convert axes.
        NF)r   r   T)rn   r   
use_dtypesr   is_axis)rO   Z_AXIS_ORDERSZ	_get_axisr!   r   _try_convert_datar   setattr)r   rO   Z	axis_nameaxZserZnew_serresultZnew_axisr^   r^   r`   r    s    


zParser._convert_axesc                 C  s   t | d S r]   r   r   r^   r^   r`   r	    s    zParser._try_convert_typesr4   r!   ztuple[Series, bool])rn   r   r
  r   r  r\   c              
   C  sR  |r| j sjtt|r|dfS t , tjddtd |tj	}W d   n1 sX0    Y  |dfS | j du rvnVt
| j tr| j |n| j }|durz||dfW S  ttfy   |df Y S 0 |r| |\}}	|	r|dfS d}
| jtjur
|s
|dfS t|j rBz|d}d}
W n ttfy@   Y n0 |j jdkr|j dkrz|d}d}
W n ttfy   Y n0 t|r|j d	v rz$|d
}||k r|}d}
W n tttfy   Y n0 |j dkr"|j d
kr"z|d
}d}
W n ttfy    Y n0 |dkrJt|rJ| jdkrJ|dfS ||
fS )zI
        Try to parse a Series into a column by inferring dtype.
        FignorezDowncasting object dtype arrayscategoryNTZfloat64f)floatobjectint64rI   rX   r   )r   allr#   r   catch_warningsfilterwarningsr   Zfillnanpnanrq   r  r   astype	TypeErrorrp   _try_convert_to_dater   r   r   r   kindr   OverflowErrorrP   )r   rn   r   r
  r   r  Zfilledr   new_datar  Z	convertedr^   r^   r`   r    st    
*




zParser._try_convert_data)r   r\   c                 C  sJ  t |s|dfS |}|jdkr(|t}|jdkrpz|d}W n. tyZ   |df Y S  ttfyn   Y n0 t|jjt	j
rt|j|| jkB |jtkB }| s|dfS | jr| jfn| j}|D ]z}zLt . tjddtd t|d|d	}W d
   n1 s
0    Y  W n tttfy4   Y qY n0 |df  S |dfS )z
        Try to parse a ndarray like into a date column.

        Try to coerce object in epoch/iso formats and integer/float in epoch
        formats. Return a boolean if parsing was successful.
        Fstringr  r  r  z=.*parsing datetimes with mixed time zones will raise an errorr  raise)r   unitNT)r   r   r  r  r   r  rp   
issubclasstyper  numberr"   Z_valuesr  r   r  rT   r   r   r  r  r   r$   )r   r   r!  Zin_rangeZ
date_unitsrT   r^   r^   r`   r  #  sF    	



2
zParser._try_convert_to_date)TTF)r   r   r   r   r   r   r   r   r   r   r  r   r  r  r	  r  r  r^   r^   r^   r`   r   e  s@   
%	

   [r   c                   @  s:   e Zd ZU dZdZded< ddddZddd	d
ZdS )r   rX   )rn   rX   r   zSeries | NonerO   rM   r   c                 C  sV   t | j| jd}| jdkrHdd | D }| | tf i || _n
t|| _d S )Nr   r   c                 S  s   i | ]\}}t ||qS r^   rH   r   kvr^   r^   r`   
<dictcomp>`  r   z'SeriesParser._parse.<locals>.<dictcomp>)r   r   r   rP   itemsr  r!   rO   )r   r   r  r^   r^   r`   r  \  s    

zSeriesParser._parsec                 C  s4   | j d u rd S | jd| j | jd\}}|r0|| _ d S )Nr   r   )rO   r  r   )r   rO   r  r^   r^   r`   r	  f  s    


zSeriesParser._try_convert_typesN)r   r   r   r}   r   r   r  r	  r^   r^   r^   r`   r   W  s
   

r   c                   @  s\   e Zd ZU dZdZded< ddddZdd
dddddZddddZddddZ	d	S )r   rk   )rk   rX   r   zDataFrame | NonerO   rM   r   c                 C  s   | j }| j}|dkr.tt|| jdd d| _n|dkrdd t|| jd D }| | dd |d D }t|t	|d |d< tf d	d i|| _nX|d
krtj
t|| jdd d
d| _n2|dkrt|| jd| _ntt|| jdd d| _d S )Nrk   r(  )r   r   c                 S  s   i | ]\}}t ||qS r^   r)  r*  r^   r^   r`   r-  ~  s   z&FrameParser._parse.<locals>.<dictcomp>c                 S  s"   g | ]}t |trt|n|qS r^   )rq   r   r   )r   colr^   r^   r`   r     s   z&FrameParser._parse.<locals>.<listcomp>r   rX   )r   rP   rm   )r   rP   r   r   r   rO   r.  r  r(   r-   	from_dictr2   )r   r   rP   r  Z
orig_namesr^   r^   r`   r  u  s<    


zFrameParser._parseNz1Callable[[Hashable, Series], tuple[Series, bool]]z!Callable[[Hashable], bool] | None)r  filtr\   c                 C  s   |du rdd }| j }|dus"J d}i }t| D ]6\}\}}||rd|||\}	}
|
rd|	}d}|||< q6|rt||jd}|j|_|| _ dS )zM
        Take a conversion function and possibly recreate the frame.
        Nc                 S  s   dS )NTr^   )r0  r^   r^   r`   r     r   z0FrameParser._process_converter.<locals>.<lambda>FTr   )rO   	enumerater.  r   rX   rk   )r   r  r2  rO   Zneeds_new_objZnew_objir0  r   r!  r  Z	new_framer^   r^   r`   _process_converter  s"    
zFrameParser._process_converterc                   s2    j d u rd S  jr     fdd d S )Nc                   s    j | |ddS )NFr/  )r  r0  r   r   r^   r`   r     r   z0FrameParser._try_convert_types.<locals>.<lambda>)rO   r   _try_convert_datesr5  r   r^   r   r`   r	    s    

zFrameParser._try_convert_typesc                   sX   j d u rd S j}t|tr"g }t| dd fdd}jfdd|d d S )NrJ   r   c                   s`   |  v rdS j sdS t| ts$dS |  }|dsX|dksX|dksX|dksX|dr\dS dS )zK
            Return if this col is ok to try for a date parse.
            TF)Z_at_timemodifieddatedatetime	timestamp)r   rq   rH   r   r   
startswith)r0  Z	col_lowerr   r   r^   r`   is_ok  s&    
z-FrameParser._try_convert_dates.<locals>.is_okc                   s
     |S r]   )r  r6  r   r^   r`   r     r   z0FrameParser._try_convert_dates.<locals>.<lambda>)r2  )rO   r   rq   rJ   r   r5  )r   Zconvert_dates_list_boolr?  r^   r>  r`   r7    s    

zFrameParser._try_convert_dates)N)
r   r   r   r}   r   r   r  r5  r	  r7  r^   r^   r^   r`   r   p  s   
' 
r   )............)............)Nrb   rc   Trd   NFre   Nr   Nrf   )j
__future__r   r   r   r   collectionsior   	itertoolsr   typingr   r	   r
   r   r   r   r   r   r   numpyr  Zpandas._libsr   Zpandas._libs.jsonr   r   Zpandas._libs.tslibsr   Zpandas.compat._optionalr   Zpandas.errorsr   Zpandas.util._decoratorsr   Zpandas.util._exceptionsr   Zpandas.util._validatorsr   Zpandas.core.dtypes.commonr   r   Zpandas.core.dtypes.dtypesr   Zpandasr   r   r   r    r!   r"   r#   r$   Zpandas.core.reshape.concatr%   Zpandas.core.shared_docsr&   Zpandas.io.commonr'   r(   r)   r*   r+   r,   r-   r.   r/   Zpandas.io.json._normalizer0   Zpandas.io.json._table_schemar1   r2   Zpandas.io.parsers.readersr3   collections.abcr4   r5   typesr6   Zpandas._typingr7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   Zpandas.core.genericrB   rC   ra   r|   rs   rt   rr   r   r   Iteratorr   r   r   r   r^   r^   r^   r`   <module>   sd  (
(
,4            .            .            ,V6P8888
8  7  5 s